Gửi email sử dụng SMTP trong Python


Python cung cấp thư viện smtplib, sử dụng như một SMTP Client để thực hiện gửi email tới một địa chỉ Email khác trên Internet thông qua giao thức SMTP.

Cài đặt thư viện smtplib

Sử dụng trình quản lý package/module PIP của Python để cài đặt.

# Python 2
pip install smtplib

# Python 3
pip3 install smtplib

Gửi email sử dụng SMTP

Đoạn script Python dưới đây sẽ thực hiện gửi email bằng giao thức SMTP từ 1 SMTP Server

#! /usr/bin/python3
import sys
from smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP                  # use this for standard SMTP protocol   (port 25, no encryption)
# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText

SMTP_Host = 'smtp.gmail.com'
sender = 'testmail@vinasupport.com'
receivers = ['user@gmail.com']
username = "testmail@vinasupport.com"
password = "your_password"

# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'

content = """\
Test SMTTP Python script
"""

subject = "Sent from vinasupport.com"

try:
    msg = MIMEText(content, text_subtype)
    msg['Subject'] = subject
    msg['From'] = sender  # some SMTP servers will do this automatically, not all

    conn = SMTP(SMTP_Host)
    conn.set_debuglevel(False)
    conn.login(username, password)
    try:
        conn.sendmail(sender, receivers, msg.as_string())
    finally:
        conn.quit()
except Exception as error:
    print(error)

Một số lỗi thường gặp

Nếu gặp lỗi khi sử dụng tài khoản Gmail

SMTPAuthenticationError (535, ‘5.7.8 Username and Password not accepted. Learn more at\n5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 sh5sm32272477pbc.21 – gsmtp’)

Nguyên nhân là do Google chặn ko cho sử dụng script/app để gửi email. Các bạn truy cập tài khoản Gmail sử dụng và kích hoạt nó lên.

Vào địa chỉ: https://myaccount.google.com/lesssecureapps

Nguồn: vinasupport.com

             
SHARE

Bài viết liên quan

mode_edit Bình luận của bạn

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

account_circle
web