Hướng dẫn python send anonymous email - python gửi email ẩn danh

Real Python has many great tutorials.

""" # Turn these into plain/html MIMEText objects part1 = MIMEText[text, "plain"] part2 = MIMEText[html, "html"] # Add HTML/plain-text parts to MIMEMultipart message # The email client will try to render the last part first message.attach[part1] message.attach[part2] # Create secure connection with server and send email context = ssl.create_default_context[] with smtplib.SMTP_SSL["smtp.gmail.com", 465, context=context] as server: server.login[sender_email, password] server.sendmail[ sender_email, receiver_email, message.as_string[] ] 1 module. For a detailed description, check the documentation.

Vì không phải tất cả các ứng dụng email hiển thị nội dung HTML theo mặc định và một số người chỉ chọn để nhận email văn bản đơn giản vì lý do bảo mật, điều quan trọng là phải bao gồm một phương pháp thay thế văn bản đơn giản cho các tin nhắn HTML. Vì ứng dụng email sẽ hiển thị tệp đính kèm nhiều phần cuối cùng trước tiên, hãy đảm bảo thêm thông báo HTML sau phiên bản văn bản đơn giản.

Trong ví dụ dưới đây, các đối tượng

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

sender_email = ""
receiver_email = ""
password = input["Type your password and press enter:"]

message = MIMEMultipart["alternative"]
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email

# Create the plain-text and HTML version of your message
text = """\
Hi,
How are you?
Real Python has many great tutorials:
www.realpython.com"""
html = """\

  
    

Hi,
How are you?
Real Python has many great tutorials.

""" # Turn these into plain/html MIMEText objects part1 = MIMEText[text, "plain"] part2 = MIMEText[html, "html"] # Add HTML/plain-text parts to MIMEMultipart message # The email client will try to render the last part first message.attach[part1] message.attach[part2] # Create secure connection with server and send email context = ssl.create_default_context[] with smtplib.SMTP_SSL["smtp.gmail.com", 465, context=context] as server: server.login[sender_email, password] server.sendmail[ sender_email, receiver_email, message.as_string[] ]
2 của chúng tôi sẽ chứa các phiên bản HTML và văn bản đơn giản của thông điệp của chúng tôi và phiên bản
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

sender_email = ""
receiver_email = ""
password = input["Type your password and press enter:"]

message = MIMEMultipart["alternative"]
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email

# Create the plain-text and HTML version of your message
text = """\
Hi,
How are you?
Real Python has many great tutorials:
www.realpython.com"""
html = """\

  
    

Hi,
How are you?
Real Python has many great tutorials.

""" # Turn these into plain/html MIMEText objects part1 = MIMEText[text, "plain"] part2 = MIMEText[html, "html"] # Add HTML/plain-text parts to MIMEMultipart message # The email client will try to render the last part first message.attach[part1] message.attach[part2] # Create secure connection with server and send email context = ssl.create_default_context[] with smtplib.SMTP_SSL["smtp.gmail.com", 465, context=context] as server: server.login[sender_email, password] server.sendmail[ sender_email, receiver_email, message.as_string[] ]
3 kết hợp chúng thành một thông báo với hai tùy chọn kết xuất thay thế:

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

sender_email = ""
receiver_email = ""
password = input["Type your password and press enter:"]

message = MIMEMultipart["alternative"]
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email

# Create the plain-text and HTML version of your message
text = """\
Hi,
How are you?
Real Python has many great tutorials:
www.realpython.com"""
html = """\

  
    

Hi,
How are you?
Real Python has many great tutorials.

""" # Turn these into plain/html MIMEText objects part1 = MIMEText[text, "plain"] part2 = MIMEText[html, "html"] # Add HTML/plain-text parts to MIMEMultipart message # The email client will try to render the last part first message.attach[part1] message.attach[part2] # Create secure connection with server and send email context = ssl.create_default_context[] with smtplib.SMTP_SSL["smtp.gmail.com", 465, context=context] as server: server.login[sender_email, password] server.sendmail[ sender_email, receiver_email, message.as_string[] ]

Trong ví dụ này, trước tiên bạn xác định thông báo văn bản đơn giản và HTML dưới dạng chuỗi chuỗi, sau đó lưu trữ chúng là ________ 84/________ 85

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

sender_email = ""
receiver_email = ""
password = input["Type your password and press enter:"]

message = MIMEMultipart["alternative"]
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email

# Create the plain-text and HTML version of your message
text = """\
Hi,
How are you?
Real Python has many great tutorials:
www.realpython.com"""
html = """\

  
    

Hi,
How are you?
Real Python has many great tutorials.

""" # Turn these into plain/html MIMEText objects part1 = MIMEText[text, "plain"] part2 = MIMEText[html, "html"] # Add HTML/plain-text parts to MIMEMultipart message # The email client will try to render the last part first message.attach[part1] message.attach[part2] # Create secure connection with server and send email context = ssl.create_default_context[] with smtplib.SMTP_SSL["smtp.gmail.com", 465, context=context] as server: server.login[sender_email, password] server.sendmail[ sender_email, receiver_email, message.as_string[] ]
6 đối tượng. Chúng có thể được thêm vào theo thứ tự này vào thông báo
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

sender_email = ""
receiver_email = ""
password = input["Type your password and press enter:"]

message = MIMEMultipart["alternative"]
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email

# Create the plain-text and HTML version of your message
text = """\
Hi,
How are you?
Real Python has many great tutorials:
www.realpython.com"""
html = """\

  
    

Hi,
How are you?
Real Python has many great tutorials.

""" # Turn these into plain/html MIMEText objects part1 = MIMEText[text, "plain"] part2 = MIMEText[html, "html"] # Add HTML/plain-text parts to MIMEMultipart message # The email client will try to render the last part first message.attach[part1] message.attach[part2] # Create secure connection with server and send email context = ssl.create_default_context[] with smtplib.SMTP_SSL["smtp.gmail.com", 465, context=context] as server: server.login[sender_email, password] server.sendmail[ sender_email, receiver_email, message.as_string[] ]
3 và được gửi qua kết nối an toàn của bạn với máy chủ email. Hãy nhớ thêm thông báo HTML sau khi thay thế văn bản đơn giản, vì các ứng dụng email sẽ cố gắng hiển thị phần phụ cuối cùng.

Thêm tệp đính kèm bằng gói
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
8

Để gửi các tệp nhị phân đến một máy chủ email được thiết kế để hoạt động với dữ liệu văn bản, chúng cần được mã hóa trước khi vận chuyển. Điều này được thực hiện phổ biến nhất bằng cách sử dụng

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

sender_email = ""
receiver_email = ""
password = input["Type your password and press enter:"]

message = MIMEMultipart["alternative"]
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email

# Create the plain-text and HTML version of your message
text = """\
Hi,
How are you?
Real Python has many great tutorials:
www.realpython.com"""
html = """\

  
    

Hi,
How are you?
Real Python has many great tutorials.

""" # Turn these into plain/html MIMEText objects part1 = MIMEText[text, "plain"] part2 = MIMEText[html, "html"] # Add HTML/plain-text parts to MIMEMultipart message # The email client will try to render the last part first message.attach[part1] message.attach[part2] # Create secure connection with server and send email context = ssl.create_default_context[] with smtplib.SMTP_SSL["smtp.gmail.com", 465, context=context] as server: server.login[sender_email, password] server.sendmail[ sender_email, receiver_email, message.as_string[] ]
9, mã hóa dữ liệu nhị phân thành các ký tự ASCII có thể in.

Ví dụ mã bên dưới cho thấy cách gửi email với tệp PDF dưới dạng tệp đính kèm:

import email, smtplib, ssl

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

subject = "An email with attachment from Python"
body = "This is an email with attachment sent from Python"
sender_email = ""
receiver_email = ""
password = input["Type your password and press enter:"]

# Create a multipart message and set headers
message = MIMEMultipart[]
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email  # Recommended for mass emails

# Add body to email
message.attach[MIMEText[body, "plain"]]

filename = "document.pdf"  # In same directory as script

# Open PDF file in binary mode
with open[filename, "rb"] as attachment:
    # Add file as application/octet-stream
    # Email client can usually download this automatically as attachment
    part = MIMEBase["application", "octet-stream"]
    part.set_payload[attachment.read[]]

# Encode file in ASCII characters to send by email    
encoders.encode_base64[part]

# Add header as key/value pair to attachment part
part.add_header[
    "Content-Disposition",
    f"attachment; filename= {filename}",
]

# Add attachment to message and convert message to string
message.attach[part]
text = message.as_string[]

# Log in to server using secure context and send email
context = ssl.create_default_context[]
with smtplib.SMTP_SSL["smtp.gmail.com", 465, context=context] as server:
    server.login[sender_email, password]
    server.sendmail[sender_email, receiver_email, text]

Thông báo

import email, smtplib, ssl

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

subject = "An email with attachment from Python"
body = "This is an email with attachment sent from Python"
sender_email = ""
receiver_email = ""
password = input["Type your password and press enter:"]

# Create a multipart message and set headers
message = MIMEMultipart[]
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email  # Recommended for mass emails

# Add body to email
message.attach[MIMEText[body, "plain"]]

filename = "document.pdf"  # In same directory as script

# Open PDF file in binary mode
with open[filename, "rb"] as attachment:
    # Add file as application/octet-stream
    # Email client can usually download this automatically as attachment
    part = MIMEBase["application", "octet-stream"]
    part.set_payload[attachment.read[]]

# Encode file in ASCII characters to send by email    
encoders.encode_base64[part]

# Add header as key/value pair to attachment part
part.add_header[
    "Content-Disposition",
    f"attachment; filename= {filename}",
]

# Add attachment to message and convert message to string
message.attach[part]
text = message.as_string[]

# Log in to server using secure context and send email
context = ssl.create_default_context[]
with smtplib.SMTP_SSL["smtp.gmail.com", 465, context=context] as server:
    server.login[sender_email, password]
    server.sendmail[sender_email, receiver_email, text]
0 chấp nhận các tham số dưới dạng các cặp khóa/giá trị kiểu RFC5233, được lưu trữ trong một từ điển và được chuyển sang phương thức
import email, smtplib, ssl

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

subject = "An email with attachment from Python"
body = "This is an email with attachment sent from Python"
sender_email = ""
receiver_email = ""
password = input["Type your password and press enter:"]

# Create a multipart message and set headers
message = MIMEMultipart[]
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email  # Recommended for mass emails

# Add body to email
message.attach[MIMEText[body, "plain"]]

filename = "document.pdf"  # In same directory as script

# Open PDF file in binary mode
with open[filename, "rb"] as attachment:
    # Add file as application/octet-stream
    # Email client can usually download this automatically as attachment
    part = MIMEBase["application", "octet-stream"]
    part.set_payload[attachment.read[]]

# Encode file in ASCII characters to send by email    
encoders.encode_base64[part]

# Add header as key/value pair to attachment part
part.add_header[
    "Content-Disposition",
    f"attachment; filename= {filename}",
]

# Add attachment to message and convert message to string
message.attach[part]
text = message.as_string[]

# Log in to server using secure context and send email
context = ssl.create_default_context[]
with smtplib.SMTP_SSL["smtp.gmail.com", 465, context=context] as server:
    server.login[sender_email, password]
    server.sendmail[sender_email, receiver_email, text]
1 của lớp cơ sở
import email, smtplib, ssl

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

subject = "An email with attachment from Python"
body = "This is an email with attachment sent from Python"
sender_email = ""
receiver_email = ""
password = input["Type your password and press enter:"]

# Create a multipart message and set headers
message = MIMEMultipart[]
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email  # Recommended for mass emails

# Add body to email
message.attach[MIMEText[body, "plain"]]

filename = "document.pdf"  # In same directory as script

# Open PDF file in binary mode
with open[filename, "rb"] as attachment:
    # Add file as application/octet-stream
    # Email client can usually download this automatically as attachment
    part = MIMEBase["application", "octet-stream"]
    part.set_payload[attachment.read[]]

# Encode file in ASCII characters to send by email    
encoders.encode_base64[part]

# Add header as key/value pair to attachment part
part.add_header[
    "Content-Disposition",
    f"attachment; filename= {filename}",
]

# Add attachment to message and convert message to string
message.attach[part]
text = message.as_string[]

# Log in to server using secure context and send email
context = ssl.create_default_context[]
with smtplib.SMTP_SSL["smtp.gmail.com", 465, context=context] as server:
    server.login[sender_email, password]
    server.sendmail[sender_email, receiver_email, text]
2.

Kiểm tra tài liệu cho mô -đun Python từ

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

sender_email = ""
receiver_email = ""
password = input["Type your password and press enter:"]

message = MIMEMultipart["alternative"]
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email

# Create the plain-text and HTML version of your message
text = """\
Hi,
How are you?
Real Python has many great tutorials:
www.realpython.com"""
html = """\

  
    

Hi,
How are you?
Real Python has many great tutorials.

""" # Turn these into plain/html MIMEText objects part1 = MIMEText[text, "plain"] part2 = MIMEText[html, "html"] # Add HTML/plain-text parts to MIMEMultipart message # The email client will try to render the last part first message.attach[part1] message.attach[part2] # Create secure connection with server and send email context = ssl.create_default_context[] with smtplib.SMTP_SSL["smtp.gmail.com", 465, context=context] as server: server.login[sender_email, password] server.sendmail[ sender_email, receiver_email, message.as_string[] ]
1 để tìm hiểu thêm về việc sử dụng các lớp MIME.

Gửi nhiều email được cá nhân hóa

Hãy tưởng tượng bạn muốn gửi email cho các thành viên trong tổ chức của bạn, để nhắc nhở họ trả phí đóng góp của họ. Hoặc có thể bạn muốn gửi sinh viên trong lớp email được cá nhân hóa của bạn với các điểm cho bài tập gần đây của họ. Những nhiệm vụ này là một làn gió trong Python.

Tạo tệp CSV với thông tin cá nhân có liên quan

Điểm bắt đầu dễ dàng để gửi nhiều email được cá nhân hóa là tạo tệp CSV [giá trị phân tách bằng dấu phẩy] chứa tất cả các thông tin cá nhân cần thiết. .

Dưới đây là nội dung của tệp

import email, smtplib, ssl

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

subject = "An email with attachment from Python"
body = "This is an email with attachment sent from Python"
sender_email = ""
receiver_email = ""
password = input["Type your password and press enter:"]

# Create a multipart message and set headers
message = MIMEMultipart[]
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email  # Recommended for mass emails

# Add body to email
message.attach[MIMEText[body, "plain"]]

filename = "document.pdf"  # In same directory as script

# Open PDF file in binary mode
with open[filename, "rb"] as attachment:
    # Add file as application/octet-stream
    # Email client can usually download this automatically as attachment
    part = MIMEBase["application", "octet-stream"]
    part.set_payload[attachment.read[]]

# Encode file in ASCII characters to send by email    
encoders.encode_base64[part]

# Add header as key/value pair to attachment part
part.add_header[
    "Content-Disposition",
    f"attachment; filename= {filename}",
]

# Add attachment to message and convert message to string
message.attach[part]
text = message.as_string[]

# Log in to server using secure context and send email
context = ssl.create_default_context[]
with smtplib.SMTP_SSL["smtp.gmail.com", 465, context=context] as server:
    server.login[sender_email, password]
    server.sendmail[sender_email, receiver_email, text]
4, mà tôi đã lưu trong cùng một thư mục với mã Python của tôi. Nó chứa tên, địa chỉ và điểm số cho một tập hợp những người hư cấu. Tôi đã sử dụng các cấu trúc
import smtplib, ssl

port = 465  # For SSL
password = input["Type your password and press enter: "]

# Create a secure SSL context
context = ssl.create_default_context[]

with smtplib.SMTP_SSL["smtp.gmail.com", port, context=context] as server:
    server.login["", password]
    # TODO: Send email here
3 để đảm bảo tất cả các email kết thúc trong hộp thư đến của riêng tôi, trong ví dụ này là:

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
0

Khi tạo tệp CSV, hãy đảm bảo tách các giá trị của bạn bằng dấu phẩy mà không có bất kỳ khoảng trắng xung quanh nào.

Vòng lặp qua hàng để gửi nhiều email

Ví dụ mã bên dưới cho bạn biết cách mở tệp CSV và lặp qua các dòng nội dung của nó [bỏ qua hàng tiêu đề]. Để đảm bảo rằng mã hoạt động chính xác trước khi bạn gửi email đến tất cả các liên hệ của mình, tôi đã in

import email, smtplib, ssl

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

subject = "An email with attachment from Python"
body = "This is an email with attachment sent from Python"
sender_email = ""
receiver_email = ""
password = input["Type your password and press enter:"]

# Create a multipart message and set headers
message = MIMEMultipart[]
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email  # Recommended for mass emails

# Add body to email
message.attach[MIMEText[body, "plain"]]

filename = "document.pdf"  # In same directory as script

# Open PDF file in binary mode
with open[filename, "rb"] as attachment:
    # Add file as application/octet-stream
    # Email client can usually download this automatically as attachment
    part = MIMEBase["application", "octet-stream"]
    part.set_payload[attachment.read[]]

# Encode file in ASCII characters to send by email    
encoders.encode_base64[part]

# Add header as key/value pair to attachment part
part.add_header[
    "Content-Disposition",
    f"attachment; filename= {filename}",
]

# Add attachment to message and convert message to string
message.attach[part]
text = message.as_string[]

# Log in to server using secure context and send email
context = ssl.create_default_context[]
with smtplib.SMTP_SSL["smtp.gmail.com", 465, context=context] as server:
    server.login[sender_email, password]
    server.sendmail[sender_email, receiver_email, text]
6 cho mỗi liên hệ, sau này chúng tôi có thể thay thế bằng chức năng thực sự gửi email:

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
1

Trong ví dụ trên, sử dụng

import email, smtplib, ssl

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

subject = "An email with attachment from Python"
body = "This is an email with attachment sent from Python"
sender_email = ""
receiver_email = ""
password = input["Type your password and press enter:"]

# Create a multipart message and set headers
message = MIMEMultipart[]
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email  # Recommended for mass emails

# Add body to email
message.attach[MIMEText[body, "plain"]]

filename = "document.pdf"  # In same directory as script

# Open PDF file in binary mode
with open[filename, "rb"] as attachment:
    # Add file as application/octet-stream
    # Email client can usually download this automatically as attachment
    part = MIMEBase["application", "octet-stream"]
    part.set_payload[attachment.read[]]

# Encode file in ASCII characters to send by email    
encoders.encode_base64[part]

# Add header as key/value pair to attachment part
part.add_header[
    "Content-Disposition",
    f"attachment; filename= {filename}",
]

# Add attachment to message and convert message to string
message.attach[part]
text = message.as_string[]

# Log in to server using secure context and send email
context = ssl.create_default_context[]
with smtplib.SMTP_SSL["smtp.gmail.com", 465, context=context] as server:
    server.login[sender_email, password]
    server.sendmail[sender_email, receiver_email, text]
7Makes chắc chắn rằng tệp của bạn đóng ở cuối khối mã.
import email, smtplib, ssl

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

subject = "An email with attachment from Python"
body = "This is an email with attachment sent from Python"
sender_email = ""
receiver_email = ""
password = input["Type your password and press enter:"]

# Create a multipart message and set headers
message = MIMEMultipart[]
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email  # Recommended for mass emails

# Add body to email
message.attach[MIMEText[body, "plain"]]

filename = "document.pdf"  # In same directory as script

# Open PDF file in binary mode
with open[filename, "rb"] as attachment:
    # Add file as application/octet-stream
    # Email client can usually download this automatically as attachment
    part = MIMEBase["application", "octet-stream"]
    part.set_payload[attachment.read[]]

# Encode file in ASCII characters to send by email    
encoders.encode_base64[part]

# Add header as key/value pair to attachment part
part.add_header[
    "Content-Disposition",
    f"attachment; filename= {filename}",
]

# Add attachment to message and convert message to string
message.attach[part]
text = message.as_string[]

# Log in to server using secure context and send email
context = ssl.create_default_context[]
with smtplib.SMTP_SSL["smtp.gmail.com", 465, context=context] as server:
    server.login[sender_email, password]
    server.sendmail[sender_email, receiver_email, text]
8 giúp dễ dàng đọc dòng tệp CSV theo từng dòng và trích xuất các giá trị của nó. Dòng
import email, smtplib, ssl

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

subject = "An email with attachment from Python"
body = "This is an email with attachment sent from Python"
sender_email = ""
receiver_email = ""
password = input["Type your password and press enter:"]

# Create a multipart message and set headers
message = MIMEMultipart[]
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email  # Recommended for mass emails

# Add body to email
message.attach[MIMEText[body, "plain"]]

filename = "document.pdf"  # In same directory as script

# Open PDF file in binary mode
with open[filename, "rb"] as attachment:
    # Add file as application/octet-stream
    # Email client can usually download this automatically as attachment
    part = MIMEBase["application", "octet-stream"]
    part.set_payload[attachment.read[]]

# Encode file in ASCII characters to send by email    
encoders.encode_base64[part]

# Add header as key/value pair to attachment part
part.add_header[
    "Content-Disposition",
    f"attachment; filename= {filename}",
]

# Add attachment to message and convert message to string
message.attach[part]
text = message.as_string[]

# Log in to server using secure context and send email
context = ssl.create_default_context[]
with smtplib.SMTP_SSL["smtp.gmail.com", 465, context=context] as server:
    server.login[sender_email, password]
    server.sendmail[sender_email, receiver_email, text]
9 bỏ qua hàng tiêu đề, do đó dòng sau
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
00 chia các hàng tiếp theo tại mỗi dấu phẩy và lưu trữ các giá trị kết quả trong chuỗi
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
01,
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
8 và
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
03 cho tiếp xúc hiện tại.

Nếu các giá trị trong tệp CSV của bạn chứa khoảng trắng ở một hoặc cả hai bên, bạn có thể xóa chúng bằng phương thức

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
04.

Nội dung cá nhân hóa

Bạn có thể đặt nội dung được cá nhân hóa vào một tin nhắn bằng cách sử dụng

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
05 để điền vào các trình giữ chỗ trong khung xoăn. Ví dụ,
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
06 sẽ cung cấp cho bạn
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
07.

Kể từ Python 3.6, định dạng chuỗi có thể được thực hiện một cách tao nhã hơn bằng cách sử dụng các chuỗi F, nhưng những điều này đòi hỏi các giữ chỗ phải được xác định trước chính F-String. Để xác định thông báo email ở đầu tập lệnh và điền vào các trình giữ chỗ cho mỗi liên hệ khi lặp qua tệp CSV, phương thức

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
08 cũ hơn được sử dụng.

Với suy nghĩ này, bạn có thể thiết lập một cơ quan thông điệp chung, với những người giữ chỗ có thể được điều chỉnh cho các cá nhân.

Mã ví dụ

Ví dụ mã sau cho phép bạn gửi email được cá nhân hóa đến nhiều liên hệ. Nó lặp qua một tệp CSV với

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
09 cho mỗi liên hệ, như trong ví dụ trên.

Thông điệp chung được xác định ở phần đầu của tập lệnh và đối với mỗi liên hệ trong tệp CSV

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
10 và
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
11 được điền vào và một email được cá nhân hóa được gửi qua kết nối an toàn với máy chủ Gmail, như bạn đã thấy trước đây:

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
2

Yagmail

Có nhiều thư viện được thiết kế để làm cho việc gửi email dễ dàng hơn, chẳng hạn như phong bì, flanker và yagmail. Yagmail được thiết kế để hoạt động cụ thể với Gmail và nó đơn giản hóa rất nhiều quá trình gửi email qua API thân thiện, như bạn có thể thấy trong ví dụ mã bên dưới:

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
3

Ví dụ mã này gửi một email với tệp đính kèm PDF trong một phần của các dòng cần thiết cho ví dụ của chúng tôi bằng cách sử dụng

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
8 và
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
7.

Khi thiết lập Yagmail, bạn có thể thêm xác nhận Gmail của mình vào Keyring của HĐH, như được mô tả trong tài liệu. Nếu bạn không làm điều này, Yagmail sẽ nhắc bạn nhập mật khẩu của mình khi được yêu cầu và lưu trữ nó tự động trong khóa.

Dịch vụ email giao dịch

Nếu bạn có kế hoạch gửi một khối lượng lớn email, muốn xem số liệu thống kê email và muốn đảm bảo giao hàng đáng tin cậy, có thể đáng để xem xét các dịch vụ email giao dịch. Mặc dù tất cả các dịch vụ sau đây đã trả tiền cho các kế hoạch gửi khối lượng email lớn, nhưng chúng cũng đi kèm với một kế hoạch miễn phí để bạn có thể dùng thử. Một số trong các gói miễn phí này là hợp lệ vô thời hạn và có thể đủ cho nhu cầu email của bạn.

Dưới đây là tổng quan về các kế hoạch miễn phí cho một số dịch vụ email giao dịch lớn. Nhấp vào tên nhà cung cấp sẽ đưa bạn đến phần định giá trên trang web của họ.

Bạn có thể chạy tìm kiếm trên Google để xem nhà cung cấp nào phù hợp nhất với nhu cầu của bạn hoặc chỉ cần thử một vài kế hoạch miễn phí để xem bạn thích làm việc với API nào.

Ví dụ mã SendGrid

Dưới đây, một ví dụ về mã để gửi email với SendGrid để cung cấp cho bạn hương vị về cách sử dụng dịch vụ email giao dịch với Python:

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: '
b'To: '
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
4

Để chạy mã này, trước tiên bạn phải:

  • Đăng ký tài khoản SendGrid [miễn phí]
  • Yêu cầu khóa API để xác thực người dùng
  • Thêm khóa API của bạn bằng cách nhập
    ---------- MESSAGE FOLLOWS ----------
    b'X-Peer: ::1'
    b''
    b'From: '
    b'To: '
    b'Subject: a local test mail'
    b''
    b'Hello there, here is a test email'
    ------------ END MESSAGE ------------
    
    14 vào dấu nhắc lệnh [để lưu trữ khóa API này vĩnh viễn] hoặc
    ---------- MESSAGE FOLLOWS ----------
    b'X-Peer: ::1'
    b''
    b'From: '
    b'To: '
    b'Subject: a local test mail'
    b''
    b'Hello there, here is a test email'
    ------------ END MESSAGE ------------
    
    15 để lưu trữ nó chỉ cho phiên khách hàng hiện tại

Thông tin thêm về cách thiết lập SendGrid cho Mac và Windows có thể được tìm thấy trong kho lưu trữ README trên GitHub.

Sự kết luận

Bây giờ bạn có thể bắt đầu kết nối SMTP an toàn và gửi nhiều email được cá nhân hóa đến những người trong danh sách liên hệ của bạn!

Bạn đã học được cách gửi email HTML với phương án thay thế theo văn bản đơn giản và đính kèm các tệp vào email của bạn. Gói Yagmail đơn giản hóa tất cả các tác vụ này khi bạn sử dụng tài khoản Gmail. Nếu bạn có kế hoạch gửi khối lượng email lớn, đáng để xem xét các dịch vụ email giao dịch.

Thích gửi email với Python và hãy nhớ: Không có thư rác xin vui lòng!

Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự. Xem cùng với hướng dẫn bằng văn bản để hiểu sâu hơn về sự hiểu biết của bạn: Gửi email với Python This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Sending Emails With Python

Bài Viết Liên Quan

Chủ Đề