Dưới đây là một số ví dụ về cách sử dụng gói để đọc, viết và gửi các tin nhắn email đơn giản cũng như các tin nhắn MIME phức tạp hơn Show Trước tiên, hãy xem cách tạo và gửi một tin nhắn văn bản đơn giản (cả nội dung văn bản và địa chỉ có thể chứa các ký tự unicode) # Import smtplib for the actual sending function import smtplib # Import the email modules we'll need from email.message import EmailMessage # Open the plain text file whose name is in textfile for reading. with open(textfile) as fp: # Create a text/plain message msg = EmailMessage() msg.set_content(fp.read()) # me == the sender's email address # you == the recipient's email address msg['Subject'] = f'The contents of {textfile}' msg['From'] = me msg['To'] = you # Send the message via our own SMTP server. s = smtplib.SMTP('localhost') s.send_message(msg) s.quit() Có thể dễ dàng phân tích các tiêu đề RFC 822 bằng cách sử dụng các lớp từ mô-đun # Import the email modules we'll need from email.parser import BytesParser, Parser from email.policy import default # If the e-mail headers are in a file, uncomment these two lines: # with open(messagefile, 'rb') as fp: # headers = BytesParser(policy=default).parse(fp) # Or for parsing headers in a string (this is an uncommon operation), use: headers = Parser(policy=default).parsestr( 'From: Foo Bar <[email protected]>\n' 'To: <[email protected]>\n' 'Subject: Test message\n' '\n' 'Body would go here\n') # Now the header items can be accessed as a dictionary: print('To: {}'.format(headers['to'])) print('From: {}'.format(headers['from'])) print('Subject: {}'.format(headers['subject'])) # You can also access the parts of the addresses: print('Recipient username: {}'.format(headers['to'].addresses[0].username)) print('Sender name: {}'.format(headers['from'].addresses[0].display_name)) Dưới đây là ví dụ về cách gửi tin nhắn MIME có chứa một loạt ảnh gia đình có thể nằm trong một thư mục # Import smtplib for the actual sending function. import smtplib # Here are the email package modules we'll need. from email.message import EmailMessage # Create the container email message. msg = EmailMessage() msg['Subject'] = 'Our family reunion' # me == the sender's email address # family = the list of all recipients' email addresses msg['From'] = me msg['To'] = ', '.join(family) msg.preamble = 'You will not see this in a MIME-aware mail reader.\n' # Open the files in binary mode. You can also omit the subtype # if you want MIMEImage to guess it. for file in pngfiles: with open(file, 'rb') as fp: img_data = fp.read() msg.add_attachment(img_data, maintype='image', subtype='png') # Send the email via our own SMTP server. with smtplib.SMTP('localhost') as s: s.send_message(msg) Đây là một ví dụ về cách gửi toàn bộ nội dung của một thư mục dưới dạng một email. #!/usr/bin/env python3 """Send the contents of a directory as a MIME message.""" import os import smtplib # For guessing MIME type based on file name extension import mimetypes from argparse import ArgumentParser from email.message import EmailMessage from email.policy import SMTP def main(): parser = ArgumentParser(description="""\ Send the contents of a directory as a MIME message. Unless the -o option is given, the email is sent by forwarding to your local SMTP server, which then does the normal delivery process. Your local machine must be running an SMTP server. """) parser.add_argument('-d', '--directory', help="""Mail the contents of the specified directory, otherwise use the current directory. Only the regular files in the directory are sent, and we don't recurse to subdirectories.""") parser.add_argument('-o', '--output', metavar='FILE', help="""Print the composed message to FILE instead of sending the message to the SMTP server.""") parser.add_argument('-s', '--sender', required=True, help='The value of the From: header (required)') parser.add_argument('-r', '--recipient', required=True, action='append', metavar='RECIPIENT', default=[], dest='recipients', help='A To: header value (at least one required)') args = parser.parse_args() directory = args.directory if not directory: directory = '.' # Create the message msg = EmailMessage() msg['Subject'] = f'Contents of directory {os.path.abspath(directory)}' msg['To'] = ', '.join(args.recipients) msg['From'] = args.sender msg.preamble = 'You will not see this in a MIME-aware mail reader.\n' for filename in os.listdir(directory): path = os.path.join(directory, filename) if not os.path.isfile(path): continue # Guess the content type based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files. ctype, encoding = mimetypes.guess_type(path) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) with open(path, 'rb') as fp: msg.add_attachment(fp.read(), maintype=maintype, subtype=subtype, filename=filename) # Now send or store the message if args.output: with open(args.output, 'wb') as fp: fp.write(msg.as_bytes(policy=SMTP)) else: with smtplib.SMTP('localhost') as s: s.send_message(msg) if __name__ == '__main__': main() Đây là một ví dụ về cách giải nén một tin nhắn MIME như ở trên, vào một thư mục tệp #!/usr/bin/env python3 """Unpack a MIME message into a directory of files.""" import os import email import mimetypes from email.policy import default from argparse import ArgumentParser def main(): parser = ArgumentParser(description="""\ Unpack a MIME message into a directory of files. """) parser.add_argument('-d', '--directory', required=True, help="""Unpack the MIME message into the named directory, which will be created if it doesn't already exist.""") parser.add_argument('msgfile') args = parser.parse_args() with open(args.msgfile, 'rb') as fp: msg = email.message_from_binary_file(fp, policy=default) try: os.mkdir(args.directory) except FileExistsError: pass counter = 1 for part in msg.walk(): # multipart/* are just containers if part.get_content_maintype() == 'multipart': continue # Applications should really sanitize the given filename so that an # email message can't be used to overwrite important files filename = part.get_filename() if not filename: ext = mimetypes.guess_extension(part.get_content_type()) if not ext: # Use a generic bag-of-bits extension ext = '.bin' filename = f'part-{counter:03d}{ext}' counter += 1 with open(os.path.join(args.directory, filename), 'wb') as fp: fp.write(part.get_payload(decode=True)) if __name__ == '__main__': main() Dưới đây là ví dụ về cách tạo thông báo HTML bằng phiên bản văn bản thuần thay thế. Để làm cho mọi thứ thú vị hơn một chút, chúng tôi bao gồm một hình ảnh có liên quan trong phần html và chúng tôi lưu một bản sao của những gì chúng tôi sẽ gửi vào đĩa, cũng như gửi nó Chúng tôi có thể gửi thư từ Python không?Python đi kèm với mô-đun smtplib tích hợp để gửi email bằng Giao thức truyền thư đơn giản (SMTP) . smtplib 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.
Gửi email bằng Python dễ dàng như thế nào?Đây là bốn bước cơ bản để gửi email bằng Python. . Thiết lập máy chủ SMTP và đăng nhập vào tài khoản của bạn Tạo đối tượng thông báo MIMEMultipart và tải nó với các tiêu đề thích hợp cho các trường From , To và Subject Thêm nội dung thư của bạn Gửi tin nhắn bằng đối tượng máy chủ SMTP Làm cách nào để gửi thư SMTP bằng Python?Để gửi thư, bạn sử dụng smtpObj để kết nối với máy chủ SMTP trên máy cục bộ, sau đó sử dụng phương thức sendmail cùng với thư, địa chỉ gửi và địa chỉ đích . (even though the from and to addresses are within the e-mail itself, these aren't always used to route mail).
Làm cách nào để gửi email HTML bằng Python?Gửi nội dung HTML cùng với email. . Nhập mô-đun. . Xác định tài liệu HTML. . Thiết lập địa chỉ email và mật khẩu. . Tạo một lớp MIMEMultipart và thiết lập các trường Từ, Đến, Chủ đề. . Đính kèm tài liệu html được xác định trước đó, dưới dạng loại nội dung html MIMEText vào thông báo MIME. . Chuyển đổi email_message thành chuỗi |