Tạo địa chỉ mac python

Bạn có thể tìm thấy hướng dẫn này vì bạn muốn gửi email bằng Python. Có lẽ bạn muốn nhận lời nhắc qua email từ mã của mình, gửi email xác nhận cho người dùng khi họ tạo tài khoản hoặc gửi email cho các thành viên trong tổ chức của bạn để nhắc họ thanh toán phí. Gửi email thủ công là một công việc tốn nhiều thời gian và dễ xảy ra lỗi, nhưng thật dễ dàng để tự động hóa bằng Python

Trong hướng dẫn này, bạn sẽ học cách

  • Thiết lập kết nối an toàn bằng cách sử dụng

    ---------- MESSAGE FOLLOWS ----------
    b'X-Peer: ::1'
    b''
    b'From: [email protected]'
    b'To: [email protected]'
    b'Subject: a local test mail'
    b''
    b'Hello there, here is a test email'
    ------------ END MESSAGE ------------
    
    5 và
    ---------- MESSAGE FOLLOWS ----------
    b'X-Peer: ::1'
    b''
    b'From: [email protected]'
    b'To: [email protected]'
    b'Subject: a local test mail'
    b''
    b'Hello there, here is a test email'
    ------------ END MESSAGE ------------
    
    6

  • Sử dụng thư viện

    ---------- MESSAGE FOLLOWS ----------
    b'X-Peer: ::1'
    b''
    b'From: [email protected]'
    b'To: [email protected]'
    b'Subject: a local test mail'
    b''
    b'Hello there, here is a test email'
    ------------ END MESSAGE ------------
    
    7 tích hợp sẵn của Python để gửi email cơ bản

  • Gửi email có nội dung HTML và tệp đính kèm bằng gói

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

  • Gửi nhiều email được cá nhân hóa bằng tệp CSV có dữ liệu liên hệ

  • Sử dụng gói Yagmail để gửi email qua tài khoản Gmail của bạn chỉ bằng một vài dòng mã

Bạn sẽ tìm thấy một số dịch vụ email giao dịch ở cuối hướng dẫn này, sẽ hữu ích khi bạn muốn gửi một số lượng lớn email

Tải xuống miễn phí. Nhận một chương mẫu từ Thủ thuật Python. Cuốn sách chỉ cho bạn các phương pháp hay nhất về Python với các ví dụ đơn giản mà bạn có thể áp dụng ngay lập tức để viết mã Pythonic + đẹp hơn

Bắt đầu

Python đi kèm với mô-đun

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
7 tích hợp để gửi email bằng Giao thức chuyển thư đơn giản (SMTP).
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
7 sử dụng giao thức RFC 821 cho SMTP. Các ví dụ trong hướng dẫn này sẽ sử dụng máy chủ SMTP của Gmail để gửi email, nhưng các nguyên tắc tương tự cũng áp dụng cho các dịch vụ email khác. Mặc dù phần lớn các nhà cung cấp dịch vụ email sử dụng các cổng kết nối giống như các cổng kết nối trong hướng dẫn này, nhưng bạn có thể chạy tìm kiếm nhanh trên Google để xác nhận cổng kết nối của mình

Để bắt đầu với hướng dẫn này, hoặc loại bỏ các email bạn gửi và in chúng ra dấu nhắc lệnh thay thế. Cả hai tùy chọn được đặt ra cho bạn dưới đây. Máy chủ gỡ lỗi SMTP cục bộ có thể hữu ích để khắc phục mọi sự cố với chức năng email và đảm bảo các chức năng email của bạn không có lỗi trước khi gửi bất kỳ email nào

Loại bỏ các quảng cáo

lựa chọn 1. Thiết lập tài khoản Gmail để phát triển

Nếu bạn quyết định sử dụng tài khoản Gmail để gửi email, tôi thực sự khuyên bạn nên thiết lập một tài khoản tạm thời để phát triển mã của mình. Điều này là do bạn sẽ phải điều chỉnh cài đặt bảo mật của tài khoản Gmail để cho phép truy cập từ mã Python của bạn và vì có khả năng bạn vô tình để lộ thông tin đăng nhập của mình. Ngoài ra, tôi thấy rằng hộp thư đến của tài khoản thử nghiệm của tôi nhanh chóng chứa đầy email thử nghiệm, đó là lý do đủ để thiết lập một tài khoản Gmail mới để phát triển

Một tính năng hay của Gmail là bạn có thể sử dụng ký hiệu

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("[email protected]", password)
    # TODO: Send email here
1 để thêm bất kỳ công cụ sửa đổi nào vào địa chỉ email của mình, ngay trước ký hiệu
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("[email protected]", password)
    # TODO: Send email here
2. Ví dụ: thư được gửi tới
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("[email protected]", password)
    # TODO: Send email here
3 và
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("[email protected]", password)
    # TODO: Send email here
4 sẽ đến tại
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("[email protected]", password)
    # TODO: Send email here
5. Khi kiểm tra chức năng email, bạn có thể sử dụng chức năng này để mô phỏng nhiều địa chỉ đều trỏ đến cùng một hộp thư đến

Để thiết lập địa chỉ Gmail để kiểm tra mã của bạn, hãy làm như sau

  • Tạo một Tài khoản Google mới
  • Bật Cho phép các ứng dụng kém an toàn hơn thành BẬT. Xin lưu ý rằng điều này giúp người khác dễ dàng truy cập vào tài khoản của bạn hơn

Nếu bạn không muốn giảm cài đặt bảo mật cho tài khoản Gmail của mình, hãy xem tài liệu của Google về cách lấy thông tin đăng nhập truy cập cho tập lệnh Python của bạn, sử dụng khung ủy quyền OAuth2

Lựa chọn 2. Thiết lập máy chủ SMTP cục bộ

Bạn có thể kiểm tra chức năng email bằng cách chạy máy chủ gỡ lỗi SMTP cục bộ, sử dụng mô-đun

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("[email protected]", password)
    # TODO: Send email here
6 được cài đặt sẵn với Python. Thay vì gửi email đến địa chỉ đã chỉ định, nó sẽ loại bỏ chúng và in nội dung của chúng ra bảng điều khiển. Chạy máy chủ gỡ lỗi cục bộ có nghĩa là không cần thiết phải xử lý mã hóa thư hoặc sử dụng thông tin xác thực để đăng nhập vào máy chủ email

Bạn có thể khởi động máy chủ gỡ lỗi SMTP cục bộ bằng cách nhập thông tin sau vào Dấu nhắc Lệnh

$ python -m smtpd -c DebuggingServer -n localhost:1025

Trên Linux, sử dụng lệnh tương tự 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("[email protected]", password)
    # TODO: Send email here
7

Mọi email được gửi qua máy chủ này sẽ bị loại bỏ và hiển thị trong cửa sổ đầu cuối dưới dạng đối tượng cho mỗi dòng

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

Đối với phần còn lại của hướng dẫn, tôi sẽ cho rằng bạn đang sử dụng tài khoản Gmail, nhưng nếu bạn đang sử dụng máy chủ gỡ lỗi cục bộ, chỉ cần đảm bảo sử dụng

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("[email protected]", password)
    # TODO: Send email here
9 làm máy chủ SMTP của bạn và sử dụng cổng 1025 thay vì cổng 465 hoặc 587. Bên cạnh đó, bạn sẽ không cần sử dụng
import smtplib, ssl

smtp_server = "smtp.gmail.com"
port = 587  # For starttls
sender_email = "[email protected]"
password = input("Type your password and press enter: ")

# Create a secure SSL context
context = ssl.create_default_context()

# Try to log in to server and send email
try:
    server = smtplib.SMTP(smtp_server,port)
    server.ehlo() # Can be omitted
    server.starttls(context=context) # Secure the connection
    server.ehlo() # Can be omitted
    server.login(sender_email, password)
    # TODO: Send email here
except Exception as e:
    # Print any error messages to stdout
    print(e)
finally:
    server.quit() 
0 hoặc mã hóa thông tin liên lạc bằng SSL/TLS

Gửi Email văn bản thuần túy

Trước khi chúng tôi đi sâu vào việc gửi email có nội dung HTML và tệp đính kèm, bạn sẽ học cách gửi email văn bản thuần túy bằng Python. Đây là những email mà bạn có thể viết trong một trình soạn thảo văn bản đơn giản. Không có những thứ ưa thích như định dạng văn bản hoặc siêu liên kết. Bạn sẽ học được điều đó một lát sau

Bắt đầu kết nối SMTP an toàn

Khi bạn gửi email qua Python, bạn nên đảm bảo rằng kết nối SMTP của bạn được mã hóa, để người khác không dễ dàng truy cập thông tin và thông tin đăng nhập của bạn. SSL (Lớp cổng bảo mật) và TLS (Bảo mật lớp vận chuyển) là hai giao thức có thể được sử dụng để mã hóa kết nối SMTP. Không cần thiết phải sử dụng một trong hai thứ này khi sử dụng máy chủ gỡ lỗi cục bộ

Có hai cách để bắt đầu kết nối an toàn với máy chủ email của bạn

  • Bắt đầu kết nối SMTP được bảo mật ngay từ đầu bằng cách sử dụng
    ---------- MESSAGE FOLLOWS ----------
    b'X-Peer: ::1'
    b''
    b'From: [email protected]'
    b'To: [email protected]'
    b'Subject: a local test mail'
    b''
    b'Hello there, here is a test email'
    ------------ END MESSAGE ------------
    
    5
  • Bắt đầu một kết nối SMTP không bảo mật mà sau đó có thể được mã hóa bằng cách sử dụng
    ---------- MESSAGE FOLLOWS ----------
    b'X-Peer: ::1'
    b''
    b'From: [email protected]'
    b'To: [email protected]'
    b'Subject: a local test mail'
    b''
    b'Hello there, here is a test email'
    ------------ END MESSAGE ------------
    
    6

Trong cả hai trường hợp, Gmail sẽ mã hóa email bằng TLS, vì đây là phiên bản kế thừa an toàn hơn của SSL. Theo Python, bạn nên sử dụng

import smtplib, ssl

smtp_server = "smtp.gmail.com"
port = 587  # For starttls
sender_email = "[email protected]"
password = input("Type your password and press enter: ")

# Create a secure SSL context
context = ssl.create_default_context()

# Try to log in to server and send email
try:
    server = smtplib.SMTP(smtp_server,port)
    server.ehlo() # Can be omitted
    server.starttls(context=context) # Secure the connection
    server.ehlo() # Can be omitted
    server.login(sender_email, password)
    # TODO: Send email here
except Exception as e:
    # Print any error messages to stdout
    print(e)
finally:
    server.quit() 
3 từ mô-đun
import smtplib, ssl

smtp_server = "smtp.gmail.com"
port = 587  # For starttls
sender_email = "[email protected]"
password = input("Type your password and press enter: ")

# Create a secure SSL context
context = ssl.create_default_context()

# Try to log in to server and send email
try:
    server = smtplib.SMTP(smtp_server,port)
    server.ehlo() # Can be omitted
    server.starttls(context=context) # Secure the connection
    server.ehlo() # Can be omitted
    server.login(sender_email, password)
    # TODO: Send email here
except Exception as e:
    # Print any error messages to stdout
    print(e)
finally:
    server.quit() 
4. Thao tác này sẽ tải các chứng chỉ CA đáng tin cậy của hệ thống, cho phép kiểm tra tên máy chủ và xác thực chứng chỉ, đồng thời cố gắng chọn các cài đặt mật mã và giao thức an toàn hợp lý

Nếu bạn muốn kiểm tra mã hóa cho email trong hộp thư đến Gmail của mình, hãy đi tới Thêm → Hiển thị bản gốc để xem loại mã hóa được liệt kê dưới tiêu đề Đã nhận

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
7 là mô-đun tích hợp sẵn của Python để gửi email đến bất kỳ máy Internet nào có trình nghe trình nghe SMTP hoặc ESMTP

Trước tiên, tôi sẽ chỉ cho bạn cách sử dụng

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
5 vì nó khởi tạo một kết nối an toàn ngay từ đầu và ngắn gọn hơn một chút so với phương án thay thế
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
6. Hãy nhớ rằng Gmail yêu cầu bạn kết nối với cổng 465 nếu sử dụng
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
5 và với cổng 587 khi sử dụng
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
6

lựa chọn 1. Sử dụng
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
5

Ví dụ mã bên dưới tạo kết nối an toàn với máy chủ SMTP của Gmail, sử dụng

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
5 của
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
7 để bắt đầu kết nối được mã hóa TLS. Bối cảnh mặc định của
import smtplib, ssl

smtp_server = "smtp.gmail.com"
port = 587  # For starttls
sender_email = "[email protected]"
password = input("Type your password and press enter: ")

# Create a secure SSL context
context = ssl.create_default_context()

# Try to log in to server and send email
try:
    server = smtplib.SMTP(smtp_server,port)
    server.ehlo() # Can be omitted
    server.starttls(context=context) # Secure the connection
    server.ehlo() # Can be omitted
    server.login(sender_email, password)
    # TODO: Send email here
except Exception as e:
    # Print any error messages to stdout
    print(e)
finally:
    server.quit() 
4 xác thực tên máy chủ và chứng chỉ của nó, đồng thời tối ưu hóa tính bảo mật của kết nối. Đảm bảo điền địa chỉ email của chính bạn thay vì
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("[email protected]", password)
    # TODO: Send email here
5

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("[email protected]", password)
    # TODO: Send email here

Sử dụng

server.sendmail(sender_email, receiver_email, message)
5 để đảm bảo rằng kết nối được đóng tự động ở cuối khối mã được thụt lề. Nếu
server.sendmail(sender_email, receiver_email, message)
6 bằng 0 hoặc không được chỉ định, thì
server.sendmail(sender_email, receiver_email, message)
7 sẽ sử dụng cổng tiêu chuẩn cho SMTP qua SSL (cổng 465)

Việc lưu trữ mật khẩu email trong mã của bạn là không an toàn, đặc biệt nếu bạn có ý định chia sẻ mật khẩu đó với người khác. Thay vào đó, hãy sử dụng

server.sendmail(sender_email, receiver_email, message)
8 để cho phép người dùng nhập mật khẩu của họ khi chạy tập lệnh, như trong ví dụ trên. Nếu bạn không muốn mật khẩu của mình hiển thị trên màn hình khi bạn nhập mật khẩu, bạn có thể nhập mô-đun
server.sendmail(sender_email, receiver_email, message)
9 và sử dụng
sender_email = "[email protected]"
receiver_email = "[email protected]"
message = """\
Subject: Hi there

This message is sent from Python."""

# Send email here
0 thay vì nhập mật khẩu mù quáng

Lựa chọn 2. Sử dụng
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
6

Thay vì sử dụng

server.sendmail(sender_email, receiver_email, message)
7 để tạo một kết nối an toàn ngay từ đầu, chúng ta có thể tạo một kết nối SMTP không an toàn và mã hóa nó bằng cách sử dụng
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
6

Để thực hiện việc này, hãy tạo một phiên bản của

sender_email = "[email protected]"
receiver_email = "[email protected]"
message = """\
Subject: Hi there

This message is sent from Python."""

# Send email here
4, gói gọn một kết nối SMTP và cho phép bạn truy cập vào các phương thức của nó. Tôi khuyên bạn nên xác định cổng và máy chủ SMTP của mình ở đầu tập lệnh để dễ dàng định cấu hình chúng

Đoạn mã bên dưới sử dụng cấu trúc

sender_email = "[email protected]"
receiver_email = "[email protected]"
message = """\
Subject: Hi there

This message is sent from Python."""

# Send email here
5, thay vì định dạng
sender_email = "[email protected]"
receiver_email = "[email protected]"
message = """\
Subject: Hi there

This message is sent from Python."""

# Send email here
6 mà chúng tôi đã sử dụng trong ví dụ trước. Để đảm bảo rằng mã của bạn không bị lỗi khi xảy ra sự cố, hãy đặt mã chính của bạn vào khối
sender_email = "[email protected]"
receiver_email = "[email protected]"
message = """\
Subject: Hi there

This message is sent from Python."""

# Send email here
7 và để khối
sender_email = "[email protected]"
receiver_email = "[email protected]"
message = """\
Subject: Hi there

This message is sent from Python."""

# Send email here
8 in bất kỳ thông báo lỗi nào tới
sender_email = "[email protected]"
receiver_email = "[email protected]"
message = """\
Subject: Hi there

This message is sent from Python."""

# Send email here
9

import smtplib, ssl

smtp_server = "smtp.gmail.com"
port = 587  # For starttls
sender_email = "[email protected]"
password = input("Type your password and press enter: ")

# Create a secure SSL context
context = ssl.create_default_context()

# Try to log in to server and send email
try:
    server = smtplib.SMTP(smtp_server,port)
    server.ehlo() # Can be omitted
    server.starttls(context=context) # Secure the connection
    server.ehlo() # Can be omitted
    server.login(sender_email, password)
    # TODO: Send email here
except Exception as e:
    # Print any error messages to stdout
    print(e)
finally:
    server.quit() 

Để xác định chính bạn với máy chủ, nên gọi

import smtplib, ssl

port = 465  # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]"  # Enter your address
receiver_email = "[email protected]"  # Enter receiver address
password = input("Type your password and press enter: ")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
0 (SMTP) hoặc ____________1 (ESMTP) sau khi tạo đối tượng
import smtplib, ssl

port = 465  # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]"  # Enter your address
receiver_email = "[email protected]"  # Enter receiver address
password = input("Type your password and press enter: ")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
2 và gọi lại sau ________6. Chức năng này được gọi ngầm bởi
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
6 và
import smtplib, ssl

port = 465  # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]"  # Enter your address
receiver_email = "[email protected]"  # Enter receiver address
password = input("Type your password and press enter: ")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
5 nếu cần, vì vậy trừ khi bạn muốn kiểm tra các phần mở rộng dịch vụ SMTP của máy chủ, không cần thiết phải sử dụng rõ ràng
import smtplib, ssl

port = 465  # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]"  # Enter your address
receiver_email = "[email protected]"  # Enter receiver address
password = input("Type your password and press enter: ")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
0 hoặc
import smtplib, ssl

port = 465  # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]"  # Enter your address
receiver_email = "[email protected]"  # Enter receiver address
password = input("Type your password and press enter: ")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
1

Loại bỏ các quảng cáo

Gửi Email văn bản thuần túy của bạn

Sau khi bạn bắt đầu kết nối SMTP an toàn bằng một trong các phương pháp trên, bạn có thể gửi email của mình bằng cách sử dụng

import smtplib, ssl

port = 465  # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]"  # Enter your address
receiver_email = "[email protected]"  # Enter receiver address
password = input("Type your password and press enter: ")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
5, điều này thực hiện gần như đúng những gì được ghi trên hộp thiếc.

server.sendmail(sender_email, receiver_email, message)

Tôi khuyên bạn nên xác định địa chỉ email và nội dung thư ở đầu tập lệnh của mình sau khi nhập để bạn có thể thay đổi chúng dễ dàng

sender_email = "[email protected]"
receiver_email = "[email protected]"
message = """\
Subject: Hi there

This message is sent from Python."""

# Send email here

Chuỗi

import smtplib, ssl

port = 465  # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]"  # Enter your address
receiver_email = "[email protected]"  # Enter receiver address
password = input("Type your password and press enter: ")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
9 bắt đầu bằng
import smtplib, ssl

port = 587  # For starttls
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]"
receiver_email = "[email protected]"
password = input("Type your password and press enter:")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
    server.ehlo()  # Can be omitted
    server.starttls(context=context)
    server.ehlo()  # Can be omitted
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
0 theo sau là hai dòng mới (
import smtplib, ssl

port = 587  # For starttls
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]"
receiver_email = "[email protected]"
password = input("Type your password and press enter:")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
    server.ehlo()  # Can be omitted
    server.starttls(context=context)
    server.ehlo()  # Can be omitted
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
1). Điều này đảm bảo
import smtplib, ssl

port = 587  # For starttls
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]"
receiver_email = "[email protected]"
password = input("Type your password and press enter:")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
    server.ehlo()  # Can be omitted
    server.starttls(context=context)
    server.ehlo()  # Can be omitted
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
2 hiển thị dưới dạng chủ đề của email và văn bản theo sau dòng mới sẽ được coi là nội dung thư

Ví dụ mã dưới đây gửi một email văn bản thuần bằng cách sử dụng

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

import smtplib, ssl

port = 465  # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]"  # Enter your address
receiver_email = "[email protected]"  # Enter receiver address
password = input("Type your password and press enter: ")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)

Để so sánh, đây là một ví dụ mã gửi email văn bản thuần túy qua kết nối SMTP được bảo mật bằng

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
6. Các dòng
import smtplib, ssl

port = 587  # For starttls
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]"
receiver_email = "[email protected]"
password = input("Type your password and press enter:")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
    server.ehlo()  # Can be omitted
    server.starttls(context=context)
    server.ehlo()  # Can be omitted
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
5 có thể được bỏ qua, vì chúng được gọi ngầm bởi
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
6 và
import smtplib, ssl

port = 465  # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]"  # Enter your address
receiver_email = "[email protected]"  # Enter receiver address
password = input("Type your password and press enter: ")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
5, nếu cần

import smtplib, ssl

port = 587  # For starttls
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]"
receiver_email = "[email protected]"
password = input("Type your password and press enter:")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
    server.ehlo()  # Can be omitted
    server.starttls(context=context)
    server.ehlo()  # Can be omitted
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)

Gửi Email ưa thích

Gói

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
8 tích hợp sẵn của Python cho phép bạn cấu trúc các email ưa thích hơn, sau đó có thể chuyển các email này bằng
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
7 như bạn đã làm. Dưới đây, bạn sẽ tìm hiểu cách sử dụng gói
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
8 để gửi email có nội dung HTML và tệp đính kèm

Bao gồm nội dung HTML

Nếu bạn muốn định dạng văn bản trong email của mình (đậm, nghiêng, v.v.) hoặc nếu bạn muốn thêm bất kỳ hình ảnh, siêu liên kết hoặc nội dung phản hồi nào thì HTML sẽ rất tiện dụng. Loại email phổ biến nhất hiện nay là email nhiều phần MIME (Multipurpose Internet Mail Extensions), kết hợp giữa HTML và văn bản thuần túy. Thông báo MIME được xử lý bởi mô-đun

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

sender_email = "[email protected]"
receiver_email = "[email protected]"
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 của Python. Để biết mô tả chi tiết, hãy kiểm tra tài liệu

Vì không phải tất cả ứng dụng email đều 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 thuần túy vì lý do bảo mật, điều quan trọng là phải bao gồm một giải pháp thay thế văn bản thuần túy cho thư 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 thuần túy

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 = "[email protected]"
receiver_email = "[email protected]"
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 thuần túy của thông báo của chúng tôi và đối tượng
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

sender_email = "[email protected]"
receiver_email = "[email protected]"
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 những điều này thành một thông báo duy nhất với hai tùy chọn hiển thị thay thế

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

sender_email = "[email protected]"
receiver_email = "[email protected]"
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 văn bản thuần túy và thông báo HTML dưới dạng chuỗi ký tự, sau đó lưu trữ chúng dưới dạng đối tượng

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

sender_email = "[email protected]"
receiver_email = "[email protected]"
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() )
4/
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

sender_email = "[email protected]"
receiver_email = "[email protected]"
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() )
5
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

sender_email = "[email protected]"
receiver_email = "[email protected]"
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. Sau đó, chúng có thể được thêm vào thư
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

sender_email = "[email protected]"
receiver_email = "[email protected]"
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 theo thứ tự này 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 giải pháp thay thế văn bản thuần túy, vì các ứng dụng email sẽ cố gắng hiển thị phần phụ cuối cùng trước

Thêm tệp đính kèm bằng gói ---------- MESSAGE FOLLOWS ---------- b'X-Peer: ::1' b'' b'From: [email protected]' b'To: [email protected]' 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 = "[email protected]"
receiver_email = "[email protected]"
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 được

Ví dụ mã bên dưới cho biết cách gửi email có 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 = "[email protected]"
receiver_email = "[email protected]"
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 = "[email protected]"
receiver_email = "[email protected]"
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ạng cặp khóa/giá trị kiểu RFC5233, được lưu trữ trong từ điển và được chuyển đến lớp cơ sở

Hãy xem tài liệu về mô-đun

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

sender_email = "[email protected]"
receiver_email = "[email protected]"
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 của Python để tìm hiểu thêm về cách sử dụng các lớp MIME

Loại bỏ các quảng cáo

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 mình để nhắc họ đóng phí đóng góp. Hoặc có thể bạn muốn gửi email cá nhân hóa cho sinh viên trong lớp kèm theo điểm cho bài tập gần đây của họ. Những nhiệm vụ này thật dễ dàng 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ị được phân tách bằng dấu phẩy) chứa tất cả thông tin cá nhân bắt buộc. (Đảm bảo không chia sẻ thông tin cá nhân của người khác khi chưa được sự đồng ý của họ. ) Tệp CSV có thể được coi là một bảng đơn giản, trong đó dòng đầu tiên thường chứa các tiêu đề cộ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 = "[email protected]"
receiver_email = "[email protected]"
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 thư mục với mã Python của mình. Nó chứa tên, địa chỉ và điểm của một nhóm người hư cấu. Tôi đã sử dụng cấu trú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 = "[email protected]"
receiver_email = "[email protected]"
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)
5 để đảm bảo rằng tất cả các email đều đến hộp thư đến của riêng tôi, trong ví dụ này là my@gmail. com

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
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 phân tách các giá trị của bạn bằng dấu phẩy, không có bất kỳ khoảng trắng xung quanh nào

Lặp lại các 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 tệp (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 địa chỉ 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 = "[email protected]"
receiver_email = "[email protected]"
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 địa chỉ liên hệ, chức năng này sau này chúng ta 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: [email protected]'
b'To: [email protected]'
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 = "[email protected]"
receiver_email = "[email protected]"
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)
7đảm bảo 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 = "[email protected]"
receiver_email = "[email protected]"
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 bạn dễ dàng đọc từng dòng tệp CSV 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 = "[email protected]"
receiver_email = "[email protected]"
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 đề, sao cho dòng tiếp theo
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
00 phân tách các hàng tiếp theo ở mỗi dấu phẩy và lưu trữ các giá trị kết quả trong các chuỗi
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
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: [email protected]'
b'To: [email protected]'
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: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
03 cho liên hệ 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 pháp

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

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

Bạn có thể đưa 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: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
05 để điền vào chỗ dành sẵn cho dấu ngoặc nhọn. Ví dụ:
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
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: [email protected]'
b'To: [email protected]'
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 dễ dàng hơn bằng cách sử dụng chuỗi f, nhưng chúng yêu cầu trình giữ chỗ phải được xác định trước chính chuỗi f. Để xác định thông báo email ở đầu tập lệnh và điền vào chỗ dành sẵn cho mỗi liên hệ khi lặp qua tệp CSV, phương pháp cũ hơn ____________08 được sử dụng

Lưu ý điều này, bạn có thể thiết lập nội dung thư chung, với các trình giữ chỗ có thể được điều chỉnh cho phù hợp với từng cá nhân

Mã ví dụ

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

Thông báo 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, các trình giữ chỗ

---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
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: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
11 của nó được điền vào và một email được cá nhân hóa sẽ đượ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: [email protected]'
b'To: [email protected]'
b'Subject: a local test mail'
b''
b'Hello there, here is a test email'
------------ END MESSAGE ------------
2

Loại bỏ các quảng cáo

thư điện tử

Có nhiều thư viện được thiết kế để giúp gửi email dễ dàng hơn, chẳng hạn như Envelopes, 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 thông 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: [email protected]'
b'To: [email protected]'
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 có tệp đính kèm PDF trong một phần nhỏ các dòng cần thiết cho chúng tôi

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

Dịch vụ email giao dịch

Nếu bạn dự định gửi một lượng lớn email, muốn xem số liệu thống kê email và muốn đảm bảo việc gửi email đáng tin cậy, bạn nên 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 đều có gói trả phí để gửi số lượng lớn email, nhưng chúng cũng đi kèm với gói miễn phí để bạn có thể dùng thử. Một số gói miễn phí này có giá trị 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 gói miễn phí cho một số dịch vụ email giao dịch chính. 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ọ

Nhà cung cấpGói miễn phí40.000 email trong 30 ngày đầu tiên của bạn, sau đó là 100/ngàySendinblue300 email/ngàyMailgun10.000 email đầu tiên miễn phíMailjet200 email/ngàyAmazon SES62.000 email/tháng

Bạn có thể 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 mình hoặc chỉ cần dùng thử một vài gói miễn phí để xem bạn thích làm việc với API nào nhất

Ví dụ về mã Sendgrid

Dưới đây là một ví dụ về mã để gửi email để 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: [email protected]'
b'To: [email protected]'
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: [email protected]'
    b'To: [email protected]'
    b'Subject: a local test mail'
    b''
    b'Hello there, here is a test email'
    ------------ END MESSAGE ------------
    
    14 trong 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: [email protected]'
    b'To: [email protected]'
    b'Subject: a local test mail'
    b''
    b'Hello there, here is a test email'
    ------------ END MESSAGE ------------
    
    15 để chỉ lưu trữ khóa cho phiên máy khách hiện tại

Bạn có thể tìm thêm thông tin về cách thiết lập Sendgrid cho Mac và Windows trong README của kho lưu trữ trên Github

Phần kết luận

Giờ đây, 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 tới những người trong danh sách liên hệ của bạn

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

Thích gửi email bằng Python và hãy nhớ. xin vui lòng không có thư rác

Đánh dấu là đã hoàn thành

Xem ngay Hướng dẫn này có một khóa học video liên quan do nhóm Real Python tạo. Xem nó cùng với hướng dẫn bằng văn bản để hiểu sâu hơn. Gửi email bằng Python

🐍 Thủ thuật Python 💌

Nhận một Thủ thuật Python ngắn và hấp dẫn được gửi đến hộp thư đến của bạn vài ngày một lần. Không có thư rác bao giờ. Hủy đăng ký bất cứ lúc nào. Được quản lý bởi nhóm Real Python

Tạo địa chỉ mac python

Gửi cho tôi thủ thuật Python »

Giới thiệu về Joska de Langen

Tạo địa chỉ mac python
Tạo địa chỉ mac python

Joska là một Ordina Pythoneer viết cho Real Python

» Thông tin thêm về Joska


Mỗi hướng dẫn tại Real Python được tạo bởi một nhóm các nhà phát triển để nó đáp ứng các tiêu chuẩn chất lượng cao của chúng tôi. Các thành viên trong nhóm đã làm việc trong hướng dẫn này là

Tạo địa chỉ mac python

Aldren

Tạo địa chỉ mac python

Brad

Tạo địa chỉ mac python

Joanna

Bậc thầy Kỹ năng Python trong thế giới thực Với quyền truy cập không giới hạn vào Python thực

Tham gia với chúng tôi và có quyền truy cập vào hàng nghìn hướng dẫn, khóa học video thực hành và cộng đồng các Pythonistas chuyên gia

Nâng cao kỹ năng Python của bạn »

Chuyên gia Kỹ năng Python trong thế giới thực
Với quyền truy cập không giới hạn vào Python thực

Tham gia với chúng tôi và có quyền truy cập vào hàng ngàn hướng dẫn, khóa học video thực hành và cộng đồng Pythonistas chuyên gia

Nâng cao kỹ năng Python của bạn »

Bạn nghĩ sao?

Đánh giá bài viết này

Tweet Chia sẻ Chia sẻ Email

Bài học số 1 hoặc điều yêu thích mà bạn đã học được là gì?

Mẹo bình luận. Những nhận xét hữu ích nhất là những nhận xét được viết với mục đích học hỏi hoặc giúp đỡ các sinh viên khác. và nhận câu trả lời cho các câu hỏi phổ biến trong cổng thông tin hỗ trợ của chúng tôi