Latest Post

Tăng thứ hạng và truy cập tự nhiên với 10 phương pháp SEO hay nhất Kiếm Tiền Online (mmo): Khái Niệm và Các Hình Thức Phổ Biến

Trong Python, chúng ta có thể sử dụng thư viện smtplib như một công cụ hỗ trợ việc gửi email thông qua giao thức SMTP. Thư viện này giúp chúng ta tạo ra một SMTP Client, cho phép kết nối và truyền thông tin email đến một địa chỉ email khác trên Internet. Điều này giúp tương tác với máy chủ SMTP để thực hiện quy trình gửi email một cách dễ dàng và hiệu quả.

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 = '[email protected]'
receivers = ['[email protected]']
username = "[email protected]"
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 atn5.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

Trả lời

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 *