Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ส่งอีเมลจากบัญชี Gmail ด้วย Python

ในบทความนี้เราจะดูวิธีส่งอีเมลพร้อมไฟล์แนบด้วย Python เพื่อส่งเมล เราไม่ต้องการไลบรารีภายนอก มีโมดูลชื่อ SMTPlib มาพร้อมกับ Python ใช้ SMTP (Simple Mail Transfer Protocol) ส่งเมล สร้าง SMTP client session objects สำหรับการส่งเมล

SMTP ต้องการ source และ destination email ids ที่ถูกต้อง และหมายเลขพอร์ต พอร์ตแตกต่างกันไปตามไซต์ ตัวอย่างเช่น สำหรับ Google พอร์ตคือ 587

ก่อนอื่นเราต้อง import โมดูลเพื่อส่งเมล:

import smtplib

ที่นี่เรายังใช้โมดูล MIME (Multipurpose Internet Mail Extension) เพื่อให้ยืดหยุ่นมากขึ้น ด้วย MIME header เราสามารถเก็บข้อมูลผู้ส่งและผู้รับและรายละเอียดอื่นๆ ได้

เราใช้บริการ Gmail ของ Google เพื่อส่งเมล ดังนั้นเราต้องการการตั้งค่าบางอย่าง (ถ้าจำเป็น) สำหรับวัตถุประสงค์ด้านความปลอดภัยของ Google หากการตั้งค่าเหล่านี้ไม่ได้ตั้ง โค้ดต่อไปนี้อาจไม่ทำงาน หาก Google ไม่รองรับการเข้าถึงจาก third-party app

เพื่ออนุญาตการเข้าถึง เราต้องตั้งค่า 'Less Secure App Access' ในบัญชี Google หาก two-step verification เปิดอยู่ เราไม่สามารถใช้ less secure access ได้

เพื่อทำ setup นี้ ไปที่ Google's Admin Console และค้นหา Less Secure App setup

ส่งอีเมลจากบัญชี Gmail ด้วย Python

ขั้นตอนการส่งเมลพร้อมไฟล์แนบด้วย SMTP (smtplib)

  • สร้าง MIME
  • เพิ่มที่อยู่อีเมลผู้ส่งและผู้รับลงใน MIME
  • เพิ่มหัวข้อเมลลงใน MIME
  • แนบ body ลงใน MIME
  • เริ่ม SMTP session ด้วยพอร์ตที่ถูกต้องพร้อมคุณสมบัติความปลอดภัย
  • Login เข้าระบบ
  • ส่งเมลและออก

ตัวอย่างโค้ด

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

mail_content = '''Hello,
This is a simple mail.
There is only text, no attachments are there
The mail is sent using Python SMTP library.
Thank You'''

# ที่อยู่อีเมลและรหัสผ่าน
sender_address = 'sender123@gmail.com'
sender_pass = 'xxxxxxxx'
receiver_address = 'receiver567@gmail.com'

# Setup the MIME
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'A test mail sent by Python. It has an attachment.'

# Body และ attachments สำหรับเมล
message.attach(MIMEText(mail_content, 'plain'))

# สร้าง SMTP session สำหรับส่งเมล
session = smtplib.SMTP('smtp.gmail.com', 587)
session.starttls()  # เปิดใช้งานความปลอดภัย
session.login(sender_address, sender_pass)
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()
print('Mail Sent')

ผลลัพธ์

D:\Python TP\Python 450\linux>python 327.Send_Mail.py
Mail Sent

ส่งอีเมลจากบัญชี Gmail ด้วย Python