Breaking News
Loading...
Tuesday, November 5, 2019

Gởi email với SMTP trong Python

11/05/2019 09:24:00 PM

SMTP là giao thức gởi mail thông dụng hiện nay. Python hỗ
trợ mặc định thư viện smtplib dùng để kết nối đến một
SMTP Server và gởi email. Tuy nhiên, việc sử dụng thư
viện này sẽ gây khó khăn cho việc định dạng và sử dụng
nên chúng ta sẽ sử dụng thư viện sender , là một thư viện
giúp định dạng và gởi email đơn giản hơn.

1. Cài đặt sender
Cài đặt từ pip như sau:
$ sudo pip install sender

2. Gởi email đơn giản
Để gởi 1 email với sender , bạn cần có tài khoản và một số
thông tin của SMTP Server trước khi gởi. Ví dụ đoạn code
để gởi 1 email từ SMTP Server của Amazon.
from sender import Mail, Message
mail = Mail(
"smtp.gmail.com",
port = 465,
username = "example@gmail.com",
password = "yourpassword",
use_tls = False,
use_ssl = True,
debug_level = False
)
msg = Message("msg subject")
msg.fromaddr = ("Vo Duy Tuan", "example@gmail.com")
msg.to = "destuser@gmail.com"
msg.body = "this is a msg plain text body"
msg.html = "<b>this is a msg text body</b>"
msg.reply_to = "example@gmail.com"
msg.charset = "utf-8"
msg.extra_headers = {}
msg.mail_options = []
msg.rcpt_options = []
# Send message
mail.send(msg)

3. Gởi email có đính kèm file
Bạn cần sử dụng thêm class Attachment để tạo
attachment.
from sender import Mail, Message, Attachment
mail = Main(...)
msg = Message(..)
# Open attached file and create Attachment object
with open("photo01.jpg") as f:
file01 = Attachment("photo01.jpg", "image/jpeg"
, f.read())
msg.attach(file01)
# Send message
mail.send(msg)

4. Tìm hiểu thêm
Bạn có thể tìm hiểu thêm về thư viện sender tại website
chính thức tại địa chỉ http://sender.readthedocs.org/

0 comments:

Post a Comment

 
Toggle Footer