Địa chỉ email, tên máy chủ lưu trữ và địa chỉ IP trong các ví dụ sau đây đã bị che khuất, nhưng nếu không thì bản ghi sẽ minh họa chính xác chuỗi lệnh và phản hồi
Gửi thư điện tử
Việc sử dụng SMTP phổ biến nhất là kết nối với máy chủ thư và gửi tin nhắn. Tên máy chủ và cổng của máy chủ thư có thể được chuyển đến hàm tạo hoặc bạn có thể sử dụng connect[] một cách rõ ràng. Sau khi kết nối, chỉ cần gọi sendmail[] với các tham số phong bì và nội dung của thư. Văn bản tin nhắn phải là một tin nhắn tuân thủ RFC 2882 được định dạng đầy đủ, vì smtplib hoàn toàn không sửa đổi nội dung hoặc tiêu đề. Điều đó có nghĩa là bạn cần tự thêm tiêu đề Từ và Đến
import smtplib import email.utils from email.mime.text import MIMEText # Create the message msg = MIMEText['This is the body of the message.'] msg['To'] = email.utils.formataddr[['Recipient', 'recipient@example.com']] msg['From'] = email.utils.formataddr[['Author', 'author@example.com']] msg['Subject'] = 'Simple test message' server = smtplib.SMTP['mail'] server.set_debuglevel[True] # show communication with the server try: server.sendmail['author@example.com', ['recipient@example.com'], msg.as_string[]] finally: server.quit[]
Trong ví dụ này, gỡ lỗi cũng được bật để hiển thị giao tiếp giữa máy khách và máy chủ. Nếu không, ví dụ sẽ không tạo ra kết quả nào cả
$ python smtplib_sendmail.py send: 'ehlo localhost.local\r\n' reply: '250-mail.example.com Hello [192.168.1.17], pleased to meet you\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250-PIPELINING\r\n' reply: '250-8BITMIME\r\n' reply: '250-SIZE\r\n' reply: '250-DSN\r\n' reply: '250-ETRN\r\n' reply: '250-AUTH GSSAPI DIGEST-MD5 CRAM-MD5\r\n' reply: '250-DELIVERBY\r\n' reply: '250 HELP\r\n' reply: retcode [250]; Msg: mail.example.com Hello [192.168.1.17], pleased to meet you ENHANCEDSTATUSCODES PIPELINING 8BITMIME SIZE DSN ETRN AUTH GSSAPI DIGEST-MD5 CRAM-MD5 DELIVERBY HELP send: 'mail FROM: size=266\r\n' reply: '250 2.1.0 .. Sender ok\r\n' reply: retcode [250]; Msg: 2.1.0 .. Sender ok send: 'rcpt TO:\r\n' reply: '250 2.1.5 .. Recipient ok\r\n' reply: retcode [250]; Msg: 2.1.5 .. Recipient ok send: 'data\r\n' reply: '354 Enter mail, end with "." on a line by itself\r\n' reply: retcode [354]; Msg: Enter mail, end with "." on a line by itself data: [354, 'Enter mail, end with "." on a line by itself'] send: 'From nobody Sun Sep 28 10:02:48 2008\r\nContent-Type: text/plain; charset="us-ascii"\r\nMIME-Version: 1.0\r\nContent-Transfer-Encoding: 7bit\r\nTo: Recipient \r\nFrom: Author \r\nSubject: Simple test message\r\n\r\nThis is the body of the message.\r\n.\r\n' reply: '250 2.0.0 m8SE2mpc015614 Message accepted for delivery\r\n' reply: retcode [250]; Msg: 2.0.0 m8SE2mpc015614 Message accepted for delivery data: [250, '2.0.0 m8SE2mpc015614 Message accepted for delivery'] send: 'quit\r\n' reply: '221 2.0.0 mail.example.com closing connection\r\n' reply: retcode [221]; Msg: 2.0.0 mail.example.com closing connection
Lưu ý rằng đối số thứ hai của sendmail[], người nhận, được truyền dưới dạng danh sách. Bạn có thể bao gồm bất kỳ số lượng địa chỉ nào trong danh sách để lần lượt gửi thư đến từng người trong số họ. Vì thông tin phong bì tách biệt với tiêu đề thư, bạn thậm chí có thể BCC ai đó bằng cách đưa họ vào đối số phương thức chứ không phải trong tiêu đề thư
Xác thực và mã hóa
Lớp SMTP cũng xử lý xác thực và mã hóa TLS [bảo mật lớp vận chuyển], khi máy chủ hỗ trợ chúng. Để xác định xem máy chủ có hỗ trợ TLS hay không, hãy gọi trực tiếp ehlo[] để xác định máy tính của bạn với máy chủ và hỏi máy chủ những tiện ích mở rộng nào khả dụng. Sau đó gọi has_extn[] để kiểm tra kết quả. Khi TLS được bắt đầu, bạn phải gọi lại ehlo[] trước khi xác thực
import smtplib import email.utils from email.mime.text import MIMEText import getpass # Prompt the user for connection info to_email = raw_input['Recipient: '] servername = raw_input['Mail server name: '] username = raw_input['Mail user name: '] password = getpass.getpass["%s's password: " % username] # Create the message msg = MIMEText['Test message from PyMOTW.'] msg.set_unixfrom['author'] msg['To'] = email.utils.formataddr[['Recipient', to_email]] msg['From'] = email.utils.formataddr[['Author', 'author@example.com']] msg['Subject'] = 'Test from PyMOTW' server = smtplib.SMTP[servername] try: server.set_debuglevel[True] # identify ourselves, prompting server for supported features server.ehlo[] # If we can encrypt this session, do it if server.has_extn['STARTTLS']: server.starttls[] server.ehlo[] # re-identify ourselves over TLS connection server.login[username, password] server.sendmail['author@example.com', [to_email], msg.as_string[]] finally: server.quit[]
Lưu ý rằng STARTTLS không xuất hiện trong danh sách tiện ích mở rộng [trong thư trả lời EHLO] sau khi TLS được bật
$ python smtplib_authenticated.py Recipient: recipient@example.com Mail server name: smtpauth.isp.net Mail user name: user@isp.net user@isp.net's password: send: 'ehlo localhost.local\r\n' reply: '250-elasmtp-isp.net Hello localhost.local []\r\n' reply: '250-SIZE 14680064\r\n' reply: '250-PIPELINING\r\n' reply: '250-AUTH PLAIN LOGIN CRAM-MD5\r\n' reply: '250-STARTTLS\r\n' reply: '250 HELP\r\n' reply: retcode [250]; Msg: elasmtp-isp.net Hello localhost.local [] SIZE 14680064 PIPELINING AUTH PLAIN LOGIN CRAM-MD5 STARTTLS HELP send: 'STARTTLS\r\n' reply: '220 TLS go ahead\r\n' reply: retcode [220]; Msg: TLS go ahead send: 'ehlo localhost.local\r\n' reply: '250-elasmtp-isp.net Hello localhost.local []\r\n' reply: '250-SIZE 14680064\r\n' reply: '250-PIPELINING\r\n' reply: '250-AUTH PLAIN LOGIN CRAM-MD5\r\n' reply: '250 HELP\r\n' reply: retcode [250]; Msg: elasmtp-isp.net Hello farnsworth.local [] SIZE 14680064 PIPELINING AUTH PLAIN LOGIN CRAM-MD5 HELP send: 'AUTH CRAM-MD5\r\n' reply: '334 PDExNjkyLjEyMjI2MTI1NzlAZWxhc210cC1tZWFseS5hdGwuc2EuZWFydGhsaW5rLm5ldD4=\r\n' reply: retcode [334]; Msg: PDExNjkyLjEyMjI2MTI1NzlAZWxhc210cC1tZWFseS5hdGwuc2EuZWFydGhsaW5rLm5ldD4= send: 'ZGhlbGxtYW5uQGVhcnRobGluay5uZXQgN2Q1YjAyYTRmMGQ1YzZjM2NjOTNjZDc1MDQxN2ViYjg=\r\n' reply: '235 Authentication succeeded\r\n' reply: retcode [235]; Msg: Authentication succeeded send: 'mail FROM: size=221\r\n' reply: '250 OK\r\n' reply: retcode [250]; Msg: OK send: 'rcpt TO:\r\n' reply: '250 Accepted\r\n' reply: retcode [250]; Msg: Accepted send: 'data\r\n' reply: '354 Enter message, ending with "." on a line by itself\r\n' reply: retcode [354]; Msg: Enter message, ending with "." on a line by itself data: [354, 'Enter message, ending with "." on a line by itself'] send: 'Content-Type: text/plain; charset="us-ascii"\r\nMIME-Version: 1.0\r\nContent-Transfer-Encoding: 7bit\r\nTo: Recipient \r\nFrom: Author \r\nSubject: Test from PyMOTW\r\n\r\nTest message from PyMOTW.\r\n.\r\n' reply: '250 OK id=1KjxNj-00032a-Ux\r\n' reply: retcode [250]; Msg: OK id=1KjxNj-00032a-Ux data: [250, 'OK id=1KjxNj-00032a-Ux'] send: 'quit\r\n' reply: '221 elasmtp-isp.net closing connection\r\n' reply: retcode [221]; Msg: elasmtp-isp.net closing connection
Xác minh địa chỉ email
Giao thức SMTP bao gồm một lệnh để hỏi máy chủ xem địa chỉ có hợp lệ không. VRFY thường bị tắt để ngăn những kẻ gửi thư rác tìm địa chỉ email hợp pháp, nhưng nếu được bật, bạn có thể hỏi máy chủ về địa chỉ và nhận mã trạng thái cho biết tính hợp lệ cùng với tên đầy đủ của người dùng, nếu có