Hướng dẫn how do i send an email using python 2022? - làm cách nào để gửi email bằng python 2022?

Bạn cần gì để gửi email với Python? Một số chương trình cơ bản và kiến ​​thức web cùng với các kỹ năng Python cơ bản. Chúng tôi cho rằng bạn đã có một ứng dụng web được xây dựng với ngôn ngữ này và bây giờ bạn cần mở rộng chức năng của nó với thông báo hoặc các tùy chọn gửi email khác.

Với nhiều ví dụ về mã, trong hướng dẫn năm 2022 này, chúng tôi sẽ hướng dẫn bạn các bước cơ bản để gửi các loại email khác nhau qua máy chủ SMTP (Giao thức chuyển thư đơn giản) bằng Python.

Lưu ý: Viết và thử nghiệm trên Python 3.6.9. Xem thêm các kho lưu trữ liên quan đến Python trên GitHub.

Những tùy chọn gửi email nào với Python có?

Hai cách chính để gửi email trong Python đang sử dụng phương thức SMTP và phương pháp thứ hai là dịch vụ email giao dịch. Hãy cùng xem xét kỹ hơn về hai người và giải nén cách họ làm việc. & NBSP;

Gửi email với Python và SMTP

Tin tốt đầu tiên về Python là trong thư viện tiêu chuẩn của nó, có một mô-đun SMTPLIB tích hợp được sử dụng để gửi email qua kết nối SMTP. Mô -đun sử dụng giao thức RFC 821 tiêu chuẩn, do đó không cần cài đặt thêm hoặc thủ thuật. & NBSP;

Gửi email với Python bằng Dịch vụ Email Giao dịch

Nếu bạn quyết định thiết lập chức năng gửi trong ứng dụng Python của bạn mà không cần SMTP tích hợp, bạn có thể tích hợp API email giao dịch của bên thứ ba.

Một trong những lý do chính để đi theo con đường này là nếu tỷ lệ phân phối mạnh là một yếu tố quan trọng đối với bạn. Hầu hết các dịch vụ API của bên thứ ba đều có các công cụ phân tích và cung cấp các cơ hội khả năng mở rộng mà bạn có thể cần khi dự án của bạn phát triển.

Gửi email trong Python: Hướng dẫn từng bước

Cách gửi email bằng SMTP

Mô-đun SMTPLIB tích hợp có thể được nhập bằng cách sử dụng câu lệnh sau:

# import the necessary components first

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
port = 2525 
smtp_server = "smtp.mailtrap.io"
login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap
sender_email = ""
receiver_email = ""
message = MIMEMultipart("alternative")
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email
# write the text/plain part
text = """\
Hi,
Check out the new post on the Mailtrap blog:
SMTP Server for Testing: Cloud-based or Local?
https://blog.mailtrap.io/2018/09/27/cloud-or-local-smtp-server/
Feel free to let us know what content would be useful for you!"""
# write the HTML part
html = """\

  
    

Hi,
Check out the new post on the Mailtrap blog:

SMTP Server for Testing: Cloud-based or Local?

Feel free to let us know what content would be useful for you!

""" # convert both parts to MIMEText objects and add them to the MIMEMultipart message part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") message.attach(part1) message.attach(part2) # send your email with smtplib.SMTP("smtp.mailtrap.io", 2525) as server: server.login(login, password) server.sendmail( sender_email, receiver_email, message.as_string() ) print('Sent')
2

Để gửi email sau, hãy tạo một đối tượng SMTP:

# import the necessary components first

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
port = 2525 
smtp_server = "smtp.mailtrap.io"
login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap
sender_email = ""
receiver_email = ""
message = MIMEMultipart("alternative")
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email
# write the text/plain part
text = """\
Hi,
Check out the new post on the Mailtrap blog:
SMTP Server for Testing: Cloud-based or Local?
https://blog.mailtrap.io/2018/09/27/cloud-or-local-smtp-server/
Feel free to let us know what content would be useful for you!"""
# write the HTML part
html = """\

  
    

Hi,
Check out the new post on the Mailtrap blog:

SMTP Server for Testing: Cloud-based or Local?

Feel free to let us know what content would be useful for you!

""" # convert both parts to MIMEText objects and add them to the MIMEMultipart message part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") message.attach(part1) message.attach(part2) # send your email with smtplib.SMTP("smtp.mailtrap.io", 2525) as server: server.login(login, password) server.sendmail( sender_email, receiver_email, message.as_string() ) print('Sent')
3

Chi tiết tham số: & NBSP;

  • Máy chủ - Đây là một đối số tùy chọn và là máy chủ đang chạy máy chủ SMTP của bạn. Địa chỉ IP của máy chủ hoặc tên miền có thể được chỉ định. & NBSP;
  • Cổng - nếu đối số máy chủ được chỉ định, chỉ định một cổng, trong đó máy chủ SMTP đang nghe. & NBSP;
  • Local_hostname - Nếu máy chủ SMTP đã sử dụng đang chạy trên máy cục bộ của bạn, chỉ định localhost. & nbsp;

Đối tượng SMTP có một phương thức thể hiện có tên SendMail được sử dụng để gửi tin nhắn và có ba tham số:

  • người gửi - chuỗi có địa chỉ của người gửi.
  • Máy thu - Danh sách các chuỗi, một cho mỗi người nhận.
  • thông báo - một thông báo dưới dạng chuỗi được định dạng theo quy định trong RFCS.

# import the necessary components first

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
port = 2525 
smtp_server = "smtp.mailtrap.io"
login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap
sender_email = ""
receiver_email = ""
message = MIMEMultipart("alternative")
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email
# write the text/plain part
text = """\
Hi,
Check out the new post on the Mailtrap blog:
SMTP Server for Testing: Cloud-based or Local?
https://blog.mailtrap.io/2018/09/27/cloud-or-local-smtp-server/
Feel free to let us know what content would be useful for you!"""
# write the HTML part
html = """\

  
    

Hi,
Check out the new post on the Mailtrap blog:

SMTP Server for Testing: Cloud-based or Local?

Feel free to let us know what content would be useful for you!

""" # convert both parts to MIMEText objects and add them to the MIMEMultipart message part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") message.attach(part1) message.attach(part2) # send your email with smtplib.SMTP("smtp.mailtrap.io", 2525) as server: server.login(login, password) server.sendmail( sender_email, receiver_email, message.as_string() ) print('Sent')
4

Để đảm bảo rằng mô -đun email đã được nhập đúng và nhận mô tả đầy đủ về các lớp và đối số của nó, hãy nhập vào phiên Python tương tác:

# import the necessary components first

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
port = 2525 
smtp_server = "smtp.mailtrap.io"
login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap
sender_email = ""
receiver_email = ""
message = MIMEMultipart("alternative")
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email
# write the text/plain part
text = """\
Hi,
Check out the new post on the Mailtrap blog:
SMTP Server for Testing: Cloud-based or Local?
https://blog.mailtrap.io/2018/09/27/cloud-or-local-smtp-server/
Feel free to let us know what content would be useful for you!"""
# write the HTML part
html = """\

  
    

Hi,
Check out the new post on the Mailtrap blog:

SMTP Server for Testing: Cloud-based or Local?

Feel free to let us know what content would be useful for you!

""" # convert both parts to MIMEText objects and add them to the MIMEMultipart message part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") message.attach(part1) message.attach(part2) # send your email with smtplib.SMTP("smtp.mailtrap.io", 2525) as server: server.login(login, password) server.sendmail( sender_email, receiver_email, message.as_string() ) print('Sent')
5

Tham khảo tài liệu Python để xem xét thêm phần còn lại của các đối tượng SMTP (ví dụ: ____ 16; ____ ____ 17, v.v.) và cách áp dụng chúng.

Dưới đây bạn có thể tìm thấy một ví dụ về tập lệnh Python đơn giản cho thấy cách người ta có thể gửi email từ SMTP cục bộ.

import smtplib
sender = ''
receivers = ['']

message = """From: From Person <>
To: To Person <>
Subject: SMTP email example


This is a test message.
"""
try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, receivers, message)         
   print("Successfully sent email")
except SMTPException:

Tuy nhiên, mã này sẽ hoạt động.

Đầu tiên, bạn sẽ cần một máy chủ SMTP hoạt động thực tế. Thứ hai, hầu hết người nhận từ chối email từ các nguồn không đáng tin cậy. Trên hết, nhận được tất cả các xác nhận và chứng nhận có liên quan cho các máy chủ khác phê duyệt email của bạn là không dễ dàng.

Sử dụng API của bên thứ ba để gửi chức năng trong ứng dụng Python của bạn là cách tốt nhất để thực hiện nó. Một giống như API email MailTrap, trong đó công việc tẻ nhạt đảm bảo email của bạn đã được gửi đã được thực hiện và không cần thiết lập máy chủ SMTP của riêng bạn.

Cách gửi email bằng API email

Với sự trợ giúp của các phân tích có thể hành động, API email của chúng tôi giúp các nhà phát triển giành quyền kiểm soát hoàn toàn khả năng gửi email của họ, cho phép gửi thông lượng gửi khoảng 10.000 email một giây.

Trước khi bạn có thể gửi bất kỳ loại email nào với MailTrap, bạn sẽ cần kết nối và xác minh tên miền của mình. Kiểm tra hướng dẫn chi tiết của chúng tôi và hướng dẫn video tiền thưởng về cách thực hiện việc này.

  1. Khi bạn đã đặt tên miền, trong phần API email, từ tab Tên miền gửi, chọn Tích hợp API/SMTP.
  2. Chọn API và từ menu thả xuống, chọn Python.
  3. Sao chép mã sẽ được hiển thị và chạy nó.
Hướng dẫn how do i send an email using python 2022? - làm cách nào để gửi email bằng python 2022?

Thử mailtrap miễn phí

Làm thế nào để gửi email HTML trong Python?

Trong hầu hết các trường hợp, bạn cần thêm một số định dạng, liên kết hoặc hình ảnh vào thông báo email của bạn. Chúng ta chỉ có thể đặt tất cả những thứ này với nội dung HTML. Với mục đích này, Python có gói email. & NBSP;

Chúng tôi sẽ đối phó với loại tin nhắn MIME, có thể kết hợp HTML/CSS và văn bản thuần túy. Trong Python, nó được xử lý bởi mô -đun email.mime. & NBSP;

Tốt hơn là viết một phiên bản văn bản và phiên bản HTML một cách riêng biệt và sau đó hợp nhất chúng với thể hiện

# import the necessary components first

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
port = 2525 
smtp_server = "smtp.mailtrap.io"
login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap
sender_email = ""
receiver_email = ""
message = MIMEMultipart("alternative")
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email
# write the text/plain part
text = """\
Hi,
Check out the new post on the Mailtrap blog:
SMTP Server for Testing: Cloud-based or Local?
https://blog.mailtrap.io/2018/09/27/cloud-or-local-smtp-server/
Feel free to let us know what content would be useful for you!"""
# write the HTML part
html = """\

  
    

Hi,
Check out the new post on the Mailtrap blog:

SMTP Server for Testing: Cloud-based or Local?

Feel free to let us know what content would be useful for you!

""" # convert both parts to MIMEText objects and add them to the MIMEMultipart message part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") message.attach(part1) message.attach(part2) # send your email with smtplib.SMTP("smtp.mailtrap.io", 2525) as server: server.login(login, password) server.sendmail( sender_email, receiver_email, message.as_string() ) print('Sent')
8. Nó có nghĩa là một thông điệp như vậy có hai tùy chọn kết xuất tương ứng. Trong trường hợp HTML được kết xuất thành công vì một số lý do, một phiên bản văn bản vẫn sẽ có sẵn. & NBSP;

Input:

# import the necessary components first

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
port = 2525 
smtp_server = "smtp.mailtrap.io"
login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap
sender_email = ""
receiver_email = ""
message = MIMEMultipart("alternative")
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email
# write the text/plain part
text = """\
Hi,
Check out the new post on the Mailtrap blog:
SMTP Server for Testing: Cloud-based or Local?
https://blog.mailtrap.io/2018/09/27/cloud-or-local-smtp-server/
Feel free to let us know what content would be useful for you!"""
# write the HTML part
html = """\

  
    

Hi,
Check out the new post on the Mailtrap blog:

SMTP Server for Testing: Cloud-based or Local?

Feel free to let us know what content would be useful for you!

""" # convert both parts to MIMEText objects and add them to the MIMEMultipart message part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") message.attach(part1) message.attach(part2) # send your email with smtplib.SMTP("smtp.mailtrap.io", 2525) as server: server.login(login, password) server.sendmail( sender_email, receiver_email, message.as_string() ) print('Sent')

Output:

Hướng dẫn how do i send an email using python 2022? - làm cách nào để gửi email bằng python 2022?

Làm thế nào để gửi email với các tệp đính kèm?

Bước tiếp theo trong việc làm chủ việc gửi email với Python là đính kèm các tệp. Các tệp đính kèm vẫn là các đối tượng MIME, nhưng chúng ta cần mã hóa chúng với mô -đun Base64 mã hóa tất cả dữ liệu nhị phân thành các ký tự ASCII.

Một vài điểm quan trọng về các tệp đính kèm:

  1. Python cho phép bạn đính kèm tiêu chuẩn .txt, định dạng văn bản phong phú và tất cả các tệp văn bản chính, hình ảnh, tệp âm thanh và thậm chí các ứng dụng. Bạn chỉ cần sử dụng lớp email thích hợp như:

    # import the necessary components first
    
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    port = 2525 
    smtp_server = "smtp.mailtrap.io"
    login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
    password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap
    sender_email = ""
    receiver_email = ""
    message = MIMEMultipart("alternative")
    message["Subject"] = "multipart test"
    message["From"] = sender_email
    message["To"] = receiver_email
    # write the text/plain part
    text = """\
    Hi,
    Check out the new post on the Mailtrap blog:
    SMTP Server for Testing: Cloud-based or Local?
    https://blog.mailtrap.io/2018/09/27/cloud-or-local-smtp-server/
    Feel free to let us know what content would be useful for you!"""
    # write the HTML part
    html = """\
    
      
        

    Hi,
    Check out the new post on the Mailtrap blog:

    SMTP Server for Testing: Cloud-based or Local?

    Feel free to let us know what content would be useful for you!

    """ # convert both parts to MIMEText objects and add them to the MIMEMultipart message part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") message.attach(part1) message.attach(part2) # send your email with smtplib.SMTP("smtp.mailtrap.io", 2525) as server: server.login(login, password) server.sendmail( sender_email, receiver_email, message.as_string() ) print('Sent')
    9or ________ 20. & nbsp;

  2. Để biết thông tin đầy đủ, hãy tham khảo phần này của tài liệu Python. Ngoài ra, bạn có thể kiểm tra các ví dụ được cung cấp bởi Python để hiểu rõ hơn. & NBSP;
  3. Hãy nhớ về kích thước tệp: Gửi tệp trên 20MB là một thông lệ xấu. & NBSP;

Trong email giao dịch, các tệp PDF được sử dụng thường xuyên nhất: chúng tôi thường nhận được biên lai, vé, thẻ lên máy bay, xác nhận đặt hàng và nhiều tài liệu liên quan đến xác thực khác. Vì vậy, hãy để xem xét cách gửi thẻ lên máy bay dưới dạng tệp PDF. & NBSP;

Input:

import smtplib

# import the corresponding modules
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

port = 2525 
smtp_server = "smtp.mailtrap.io"
login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap

subject = "An example of boarding pass"
sender_email = ""
receiver_email = ""

message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject

# Add body to email
body = "This is an example of how you can send a boarding pass in attachment with Python"
message.attach(MIMEText(body, "plain"))

filename = "yourBP.pdf"
# Open PDF file in binary mode

# We assume that the file is in the directory where you run your Python script from
with open(filename, "rb") as attachment:
    # The content type "application/octet-stream" means that a MIME attachment is a binary file
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())

# Encode to base64
encoders.encode_base64(part)

# Add header 
part.add_header(
    "Content-Disposition",
    f"attachment; filename= {filename}",
)

# Add attachment to your message and convert it to string
message.attach(part)
text = message.as_string()

# send your email
with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
    server.login(login, password)
    server.sendmail(
        sender_email, receiver_email, text
    )
print('Sent') 

Output:

Hướng dẫn how do i send an email using python 2022? - làm cách nào để gửi email bằng python 2022?

Để đính kèm một số tệp, bạn có thể gọi phương thức

import smtplib

# import the corresponding modules
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

port = 2525 
smtp_server = "smtp.mailtrap.io"
login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap

subject = "An example of boarding pass"
sender_email = ""
receiver_email = ""

message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject

# Add body to email
body = "This is an example of how you can send a boarding pass in attachment with Python"
message.attach(MIMEText(body, "plain"))

filename = "yourBP.pdf"
# Open PDF file in binary mode

# We assume that the file is in the directory where you run your Python script from
with open(filename, "rb") as attachment:
    # The content type "application/octet-stream" means that a MIME attachment is a binary file
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())

# Encode to base64
encoders.encode_base64(part)

# Add header 
part.add_header(
    "Content-Disposition",
    f"attachment; filename= {filename}",
)

# Add attachment to your message and convert it to string
message.attach(part)
text = message.as_string()

# send your email
with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
    server.login(login, password)
    server.sendmail(
        sender_email, receiver_email, text
    )
print('Sent') 
1 nhiều lần., you can call the
import smtplib

# import the corresponding modules
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

port = 2525 
smtp_server = "smtp.mailtrap.io"
login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap

subject = "An example of boarding pass"
sender_email = ""
receiver_email = ""

message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject

# Add body to email
body = "This is an example of how you can send a boarding pass in attachment with Python"
message.attach(MIMEText(body, "plain"))

filename = "yourBP.pdf"
# Open PDF file in binary mode

# We assume that the file is in the directory where you run your Python script from
with open(filename, "rb") as attachment:
    # The content type "application/octet-stream" means that a MIME attachment is a binary file
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())

# Encode to base64
encoders.encode_base64(part)

# Add header 
part.add_header(
    "Content-Disposition",
    f"attachment; filename= {filename}",
)

# Add attachment to your message and convert it to string
message.attach(part)
text = message.as_string()

# send your email
with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
    server.login(login, password)
    server.sendmail(
        sender_email, receiver_email, text
    )
print('Sent') 
1 method several times.

Làm thế nào để gửi email cho nhiều người nhận bằng Python?

Gửi nhiều email cho những người nhận khác nhau và biến họ thành cá nhân là điều đặc biệt về email trong Python. & NBSP;

Để thêm một số người nhận, bạn chỉ có thể nhập địa chỉ của họ được phân tách bằng dấu phẩy và thêm CC và BCC. Nhưng nếu bạn làm việc với gửi email hàng loạt, Python sẽ giúp bạn tiết kiệm bằng các vòng. & NBSP;

Một trong những tùy chọn là tạo cơ sở dữ liệu ở định dạng .csv (chúng tôi giả sử nó được lưu vào cùng một thư mục với tập lệnh Python của bạn). & NBSP;.csv format (we assume it is saved to the same folder as your Python script). 

Chúng ta thường thấy tên của chúng ta trong các ví dụ giao dịch hoặc thậm chí quảng cáo. Đây là cách chúng ta có thể làm cho nó với Python.

Hãy để tổ chức danh sách trong một bảng đơn giản chỉ với hai cột: tên và địa chỉ email. Nó sẽ trông giống như ví dụ sau:

#name,email
John Johnson,
Peter Peterson,

Mã bên dưới sẽ mở tệp và lặp qua các hàng của nó từng dòng, thay thế {name} bằng giá trị từ cột tên tên tên.

Input:

import csv, smtplib

port = 2525 
smtp_server = "smtp.mailtrap.io"
login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap

message = """Subject: Order confirmation
To: {recipient}
From: {sender}

Hi {name}, thanks for your order! We are processing it now and will contact you soon"""
sender = ""
with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
    server.login(login, password)
    with open("contacts.csv") as file:
        reader = csv.reader(file)
        next(reader)  # it skips the header row
        for name, email in reader:
            server.sendmail(
               sender,
                email,
                message.format(name=name, recipient=email, sender=sender)
            )
            print(f'Sent to {name}')

Sau khi chạy tập lệnh, chúng tôi nhận được phản hồi sau:

Sent to John Johnson
Sent to Peter Peterson
>>> 

Output:

Trong hộp thư đến MailTrap của chúng tôi, chúng tôi thấy hai tin nhắn: một cho John Johnson và một cho Peter Peterson, đã gửi đồng thời:

Hướng dẫn how do i send an email using python 2022? - làm cách nào để gửi email bằng python 2022?

Cách gửi email với hình ảnh? & NBSP;

Hình ảnh, ngay cả khi chúng là một phần của thân thông báo email, vẫn còn đính kèm. Có ba loại trong số chúng:

  • Tệp đính kèm CID (được nhúng như một đối tượng MIME) & NBSP;
  • Base64 Hình ảnh (nhúng nội tuyến)
  • Hình ảnh được liên kết & nbsp;

Chúng tôi đã mô tả đặc thù, ưu và nhược điểm của họ và khả năng tương thích với hầu hết các ứng dụng email trong bài đăng này. & NBSP;

Để thêm tệp đính kèm CID, chúng tôi sẽ tạo một thông báo MIME Multiart với thành phần mimimeMage: we will create a MIME multipart message with MIMEImage component:

# import all necessary components
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

port = 2525
smtp_server = "smtp.mailtrap.io"
login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap

sender_email = ""
receiver_email = ""
message = MIMEMultipart("alternative")
message["Subject"] = "CID image test"
message["From"] = sender_email
message["To"] = receiver_email

# write the HTML part
html = """\

 
   
 

"""

part = MIMEText(html, "html")
message.attach(part)

# We assume that the image file is in the same directory that you run your Python script from
fp = open('mailtrap.jpg', 'rb')
image = MIMEImage(fp.read())
fp.close()

# Specify the  ID according to the img src in the HTML part
image.add_header('Content-ID', '')
message.attach(image)

# send your email
with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
   server.login(login, password)
   server.sendmail(
       sender_email, receiver_email, message.as_string()
   )
print('Sent')

Output:

Hướng dẫn how do i send an email using python 2022? - làm cách nào để gửi email bằng python 2022?

Hình ảnh CID được hiển thị như một phần của thông báo HTML và là một tệp đính kèm. Tin nhắn với loại hình ảnh này thường được coi là thư rác: Kiểm tra tab Analytics trong MailTrap để xem tỷ lệ thư rác và khuyến nghị để cải thiện. Trong hầu hết các trường hợp, nhiều ứng dụng email & nbsp; - Gmail nói riêng - don lồng hiển thị hình ảnh CID. Vì vậy, hãy để xem xét cách nhúng hình ảnh được mã hóa base64.how to embed a base64 encoded image.

Ở đây chúng tôi sẽ sử dụng mô -đun Base64 và thử nghiệm cùng một tệp hình ảnh: and experiment with the same image file:

# import the necessary components first
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import base64

port = 2525
smtp_server = "smtp.mailtrap.io"
login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap

sender_email = ""
receiver_email = ""
message = MIMEMultipart("alternative")
message["Subject"] = "inline embedding"
message["From"] = sender_email
message["To"] = receiver_email

# We assume that the image file is in the same directory that you run your Python script from
encoded = base64.b64encode(open("mailtrap.jpg", "rb").read()).decode()

html = f"""\

 
   
 

"""

part = MIMEText(html, "html")
message.attach(part)

# send your email
with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
   server.login(login, password)
   server.sendmail(
       sender_email, receiver_email, message.as_string()
   )
print('Sent')

Output:

Hướng dẫn how do i send an email using python 2022? - làm cách nào để gửi email bằng python 2022?

Bây giờ hình ảnh được nhúng vào thông báo HTML và không có sẵn dưới dạng tệp đính kèm. Python đã mã hóa hình ảnh JPG của chúng tôi và nếu chúng tôi đi đến tab Nguồn HTML, chúng tôi sẽ thấy chuỗi dữ liệu hình ảnh dài trong IMG SRC. & NBSP;

Gửi email với Python qua Gmail

Bạn có thể định cấu hình máy chủ sản xuất của mình khi sẵn sàng gửi email tùy chỉnh của mình đến địa chỉ email của người nhận thực sự. Nó cũng phụ thuộc vào nhu cầu, mục tiêu và sở thích của bạn: máy chủ cục bộ của bạn hoặc bất kỳ SMTP bên ngoài. & NBSP;

Một trong những tùy chọn phổ biến nhất là Gmail, vì vậy, hãy để xem xét kỹ hơn về nó. & NBSP;

Chúng ta thường thấy các tiêu đề như Cách làm thế nào để thiết lập một tài khoản Gmail để phát triển. Điều đó có nghĩa là bạn sẽ tạo một tài khoản Google mới và sử dụng nó cho một mục đích cụ thể. & NBSP;

Để có thể gửi email qua tài khoản Gmail của bạn, bạn cần cung cấp quyền truy cập vào nó cho ứng dụng của bạn. Bạn có thể cho phép các ứng dụng ít an toàn hơn hoặc tận dụng giao thức ủy quyền OAuth2. Nó khó khăn hơn nhưng được khuyến nghị vì lý do bảo mật. & NBSP;

Hơn nữa, để sử dụng máy chủ SMTP Gmail, bạn cần biết:

  • Tên máy chủ = smtp.gmail.com
  • Cổng = 465 cho kết nối SSL/TLS (ưu tiên)
  • hoặc port = 587 cho kết nối starttls
  • Tên người dùng = Địa chỉ email Gmail của bạn
  • Mật khẩu = Mật khẩu của bạn
import smtplib, ssl

port = 465  
password = input("your password")
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
    server.login("", password)

Nếu bạn có xu hướng đơn giản, thì bạn có thể sử dụng Yagmail, Gmail/SMTP chuyên dụng. Nó làm cho email gửi thực sự dễ dàng. Chỉ cần so sánh các ví dụ trên với một số dòng mã sau:

import yagmail
yag = yagmail.SMTP()
contents = [
    "This is the body, and here is just text http://somedomain/image.png",
    "You can find an audio file attached.", '/local/path/to/song.mp3'
]
yag.send('', 'subject', contents)

Kiểm tra email với hộp cát email mailtrap

Khi tạo một ứng dụng mới hoặc thêm bất kỳ chức năng nào, đặc biệt là khi thực hiện nó lần đầu tiên, nó rất cần thiết để thử nghiệm trên máy chủ thử nghiệm. Dưới đây là một danh sách ngắn gọn về các lý do:

  1. Bạn đã giành được những người bạn của bạn và khách hàng của bạn. Điều này rất quan trọng khi bạn kiểm tra gửi email hàng loạt hoặc làm việc với cơ sở dữ liệu email.
  2. Bạn đã giành được dòng hộp thư đến của bạn với các email thử nghiệm. & NBSP;
  3. Miền của bạn đã giành được danh sách đen cho thư rác.

Môi trường máy chủ SMTP thử nghiệm bắt chước công việc của máy chủ web của bên thực hiện thực. Trong các ví dụ sau, chúng tôi sẽ sử dụng hộp cát email MailTrap, cho phép các nhà phát triển thu được lưu lượng truy cập SMTP từ việc dàn dựng và kiểm tra và gỡ lỗi email trước khi họ đi ra cho người nhận thực tế.

Trên hết, hộp cát email có thể giúp xác thực HTML/CSS của bạn, phân tích nội dung email và đưa ra điểm spam có liên quan. Hộp cát rất dễ thiết lập; Tất cả những gì bạn cần là sao chép thông tin đăng nhập được tạo bởi ứng dụng và dán chúng vào mã của bạn.

Hướng dẫn how do i send an email using python 2022? - làm cách nào để gửi email bằng python 2022?

Đây là cách nó trông như thế nào trong thực tế:

# import the necessary components first

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
port = 2525 
smtp_server = "smtp.mailtrap.io"
login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap
sender_email = ""
receiver_email = ""
message = MIMEMultipart("alternative")
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email
# write the text/plain part
text = """\
Hi,
Check out the new post on the Mailtrap blog:
SMTP Server for Testing: Cloud-based or Local?
https://blog.mailtrap.io/2018/09/27/cloud-or-local-smtp-server/
Feel free to let us know what content would be useful for you!"""
# write the HTML part
html = """\

  
    

Hi,
Check out the new post on the Mailtrap blog:

SMTP Server for Testing: Cloud-based or Local?

Feel free to let us know what content would be useful for you!

""" # convert both parts to MIMEText objects and add them to the MIMEMultipart message part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") message.attach(part1) message.attach(part2) # send your email with smtplib.SMTP("smtp.mailtrap.io", 2525) as server: server.login(login, password) server.sendmail( sender_email, receiver_email, message.as_string() ) print('Sent')
0

MailTrap làm cho mọi thứ thậm chí dễ dàng hơn. Chuyển đến phần Tích hợp trong tab Cài đặt SMTP và lấy mẫu sẵn sàng sử dụng của tin nhắn văn bản đơn giản với thông tin đăng nhập MailTrap của bạn. Tùy chọn cơ bản nhất để hướng dẫn mã Python của bạn về người gửi gì cho ai là phương thức

import smtplib

# import the corresponding modules
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

port = 2525 
smtp_server = "smtp.mailtrap.io"
login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap

subject = "An example of boarding pass"
sender_email = ""
receiver_email = ""

message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject

# Add body to email
body = "This is an example of how you can send a boarding pass in attachment with Python"
message.attach(MIMEText(body, "plain"))

filename = "yourBP.pdf"
# Open PDF file in binary mode

# We assume that the file is in the directory where you run your Python script from
with open(filename, "rb") as attachment:
    # The content type "application/octet-stream" means that a MIME attachment is a binary file
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())

# Encode to base64
encoders.encode_base64(part)

# Add header 
part.add_header(
    "Content-Disposition",
    f"attachment; filename= {filename}",
)

# Add attachment to your message and convert it to string
message.attach(part)
text = message.as_string()

# send your email
with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
    server.login(login, password)
    server.sendmail(
        sender_email, receiver_email, text
    )
print('Sent') 
2Instance:

Hướng dẫn how do i send an email using python 2022? - làm cách nào để gửi email bằng python 2022?

Đoạn mã có vẻ khá đơn giản, phải không? Hãy cùng xem xét kỹ hơn về nó và thêm một số xử lý lỗi (xem #Explanations ở giữa). Để bắt lỗi, chúng tôi sử dụng các khối thử và các khối ngoại trừ. Tham khảo tài liệu để biết danh sách các ngoại lệ ở đây. & NBSP;

# import the necessary components first

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
port = 2525 
smtp_server = "smtp.mailtrap.io"
login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap
sender_email = ""
receiver_email = ""
message = MIMEMultipart("alternative")
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email
# write the text/plain part
text = """\
Hi,
Check out the new post on the Mailtrap blog:
SMTP Server for Testing: Cloud-based or Local?
https://blog.mailtrap.io/2018/09/27/cloud-or-local-smtp-server/
Feel free to let us know what content would be useful for you!"""
# write the HTML part
html = """\

  
    

Hi,
Check out the new post on the Mailtrap blog:

SMTP Server for Testing: Cloud-based or Local?

Feel free to let us know what content would be useful for you!

""" # convert both parts to MIMEText objects and add them to the MIMEMultipart message part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") message.attach(part1) message.attach(part2) # send your email with smtplib.SMTP("smtp.mailtrap.io", 2525) as server: server.login(login, password) server.sendmail( sender_email, receiver_email, message.as_string() ) print('Sent')
1

Khi bạn nhận được kết quả đã gửi trong shell, bạn sẽ thấy tin nhắn của mình trong hộp thư đến mailtrap của bạn:

Hướng dẫn how do i send an email using python 2022? - làm cách nào để gửi email bằng python 2022?

Nếu bạn thích làm việc trong môi trường địa phương, máy chủ gỡ lỗi SMTP cục bộ có thể là một tùy chọn. Với mục đích này, Python cung cấp một mô -đun SMTPD. Nó có tính năng DebugGingServer, sẽ loại bỏ các tin nhắn bạn đang gửi và sẽ in chúng vào stdout. Nó tương thích với tất cả các hệ thống hoạt động.

Đặt máy chủ SMTP của bạn thành LocalHost: 1025

import smtplib

# import the corresponding modules
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

port = 2525 
smtp_server = "smtp.mailtrap.io"
login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap

subject = "An example of boarding pass"
sender_email = ""
receiver_email = ""

message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject

# Add body to email
body = "This is an example of how you can send a boarding pass in attachment with Python"
message.attach(MIMEText(body, "plain"))

filename = "yourBP.pdf"
# Open PDF file in binary mode

# We assume that the file is in the directory where you run your Python script from
with open(filename, "rb") as attachment:
    # The content type "application/octet-stream" means that a MIME attachment is a binary file
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())

# Encode to base64
encoders.encode_base64(part)

# Add header 
part.add_header(
    "Content-Disposition",
    f"attachment; filename= {filename}",
)

# Add attachment to your message and convert it to string
message.attach(part)
text = message.as_string()

# send your email
with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
    server.login(login, password)
    server.sendmail(
        sender_email, receiver_email, text
    )
print('Sent') 
3

Để chạy máy chủ email SMTP trên cổng số 25, bạn sẽ cần quyền root:

import smtplib

# import the corresponding modules
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

port = 2525 
smtp_server = "smtp.mailtrap.io"
login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap

subject = "An example of boarding pass"
sender_email = ""
receiver_email = ""

message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject

# Add body to email
body = "This is an example of how you can send a boarding pass in attachment with Python"
message.attach(MIMEText(body, "plain"))

filename = "yourBP.pdf"
# Open PDF file in binary mode

# We assume that the file is in the directory where you run your Python script from
with open(filename, "rb") as attachment:
    # The content type "application/octet-stream" means that a MIME attachment is a binary file
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())

# Encode to base64
encoders.encode_base64(part)

# Add header 
part.add_header(
    "Content-Disposition",
    f"attachment; filename= {filename}",
)

# Add attachment to your message and convert it to string
message.attach(part)
text = message.as_string()

# send your email
with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
    server.login(login, password)
    server.sendmail(
        sender_email, receiver_email, text
    )
print('Sent') 
4

Nó sẽ giúp bạn xác minh xem mã của bạn có hoạt động hay không và chỉ ra các vấn đề có thể xảy ra nếu có. Tuy nhiên, nó đã giành chiến thắng cho phép bạn kiểm tra cách hiển thị mẫu email HTML của bạn.

Các bước tiếp theo với các email trong Python

Chúng tôi đã chứng minh chỉ các tùy chọn cơ bản của việc gửi email với Python để mô tả logic và một loạt các khả năng của nó. Chúng tôi khuyên bạn nên xem xét tài liệu Python và thử nghiệm mã của riêng bạn để có kết quả tuyệt vời!

Có một loạt các khung và thư viện Python khác nhau giúp tạo ra các ứng dụng thanh lịch và tận tâm hơn. Cụ thể, một số trong số họ có thể giúp cải thiện trải nghiệm của bạn với việc xây dựng chức năng gửi email:

Các khung phổ biến nhất là:

  1. Flask, cung cấp một giao diện đơn giản để gửi email gửi thư. Hãy tìm hiểu thêm trong hướng dẫn của chúng tôi về cách gửi email bằng bình.
  2. Django có thể là một lựa chọn tuyệt vời để xây dựng các mẫu HTML. Ngoài ra, hãy xem hướng dẫn gửi email Django của chúng tôi.
  3. Zope có ích để phát triển trang web. & NBSP;
  4. Mailer Marrow là một khung gửi thư chuyên dụng thêm các cấu hình hữu ích khác nhau.
  5. Plotly và dấu gạch ngang của nó có thể giúp các biểu đồ và báo cáo gửi thư.

Chúc may mắn, và don không quên ở bên an toàn khi gửi email của bạn!

Làm cách nào để gửi email bằng Python?

Thiết lập kết nối an toàn bằng smtp_ssl () và .starttls () Sử dụng thư viện smtplib tích hợp của Python để gửi email cơ bản. Gửi email với nội dung HTML và tệp đính kèm bằng gói email. Gửi nhiều email được cá nhân hóa bằng tệp CSV với dữ liệu liên hệ. Use Python's built-in smtplib library to send basic emails. Send emails with HTML content and attachments using the email package. Send multiple personalized emails using a CSV file with contact data.

Làm thế nào để bạn tự động hóa một thư điện tử trong Python?

Làm thế nào để gửi email tự động với kết quả phân tích bằng Python ?..
Yêu cầu hệ thống..
Bước 1: Kết nối với Gmail và đăng nhập ..
Bước 2: Gửi email văn bản đơn giản qua mã ..
Bước 3: Gửi email với tệp đính kèm thông qua mã ..
Bước 4: Viết chi tiết email hộp thư đến cho CSV bằng thư viện pyzmail ..

Làm thế nào để tôi SMTP trong Python?

Tạo và gửi một email đơn giản..
Tạo một đối tượng SMTP để kết nối với máy chủ ..
Đăng nhập vào tài khoản của bạn..
Xác định tiêu đề tin nhắn và thông tin đăng nhập của bạn ..
Tạo một đối tượng tin nhắn Mimemultipart và đính kèm các tiêu đề có liên quan vào nó, tức là từ, đến và chủ đề ..
Đính kèm tin nhắn vào đối tượng Mimemultipart ..

Làm cách nào để gửi thư từ Outlook bằng Python?

Tự động hóa email..
Tạo email mới.Mã này đơn giản và dễ hiểu.....
Chỉ định các thuộc tính email.....
2.1 Đặt chủ đề email.....
2.2 Đặt email máy thu.....
2.3 Thêm hình ảnh.....
2.4 Viết nội dung email.....
2.5 Thêm tệp đính kèm Excel.....
Gửi email ..