Python Send mail (go)

Source: Internet
Author: User

SMTP Send mail read: 90274

SMTP is the protocol that sends messages, and Python's built-in support for SMTP can send plain text messages, HTML messages, and messages with Attachments.

Python supports SMTP with smtplib email two modules, which are email responsible for structuring the message and smtplib sending the Message.

first, Let's construct one of the simplest plain text messages:

from email.mime.text import MIMETextmsg = MIMEText(‘hello, send by Python...‘, ‘plain‘, ‘utf-8‘)

Notice that when the object is constructed MIMEText , the first parameter is the message body, the second parameter is the MIME subtype, the ‘plain‘ final mime is ‘text/plain‘ , and finally, it must be utf-8 encoded to ensure multi-language Compatibility.

then, send it out via smtp:

 # Enter email address and password: from_addr = raw_input ( ' password: ') # Enter SMTP server address: smtp_server = raw_input (  ' SMTP server: ') # Enter recipient address: to_addr = raw_input (import Smtplibserver = smtplib. SMTP (smtp_server, 25) # SMTP protocol The default port is 25server.set_debuglevel (1) server.login (from_addr, password) server.sendmail (from_addr, [to_addr], msg.as_string ()) server.quit () 

We set_debuglevel(1) can print out all the information that interacts with the SMTP Server. The SMTP protocol is a simple text command and Response. login()method is used to log on to the SMTP server by sendmail() sending an email, because it can be sent to more than one person at a time, so the list message body is one str , the as_string() MIMEText object becomes str .

If all goes well, you can receive the email we just sent in the Recipient's mailbox:

After careful observation, the following problems are Found:

    1. The message has no subject;
    2. The Recipient's name is not displayed as a friendly name, for example Mr Green <[email protected]> ;
    3. Obviously received the message, but the prompt is not in the Recipient.

This is because the message subject, how to display the sender, the recipient, and so on is not sent through the SMTP protocol to the mta, but is included in the text sent to the mta, so we have to put From , To and Subject add to MIMEText , is a complete message:

#-*-coding:utf-8-*-From emailImport encodersFrom Email.headerImport HeaderFrom Email.mime.textImport MimetextFrom Email.utilsImport parseaddr, formataddrImport SmtplibDef_format_addr(s): name, addr = parseaddr (s)return formataddr (Header (name,' Utf-8 '). encode (), addr.encode (' Utf-8 ')If Isinstance (addr, Unicode)else Addr)) from_addr = Raw_input ( ' from: ') password = raw_input ( ' password: ') to_addr = raw_input ( ' to: ') smtp_server = raw_input ( ' smtp Server: ') msg = mimetext ( ' plain ',  ' utf-8 ') msg[u ' python enthusiast <%s> '% from_addr) msg[ ' to '] = _ Format_addr (u ' admin <%s> '% to_addr) msg[ ' Subject '] = Header (u ' Greetings from SMTP ... ',  ' utf-8 '). encode () server = smtplib. SMTP (smtp_server, 25) server.set_debuglevel (1) server.login (from_addr, Password) server.sendmail (from_addr, [to_addr], msg.as_string ()) server.quit ()      

We have written a function _format_addr() to format an email address. Note that you cannot simply pass name <[email protected]> in, because if you include chinese, you need to encode through the Header object.

msg[‘To‘]You receive a string instead of a list, and if you have multiple e-mail addresses, , you can use Separate.

Once you send the message again, you'll see the correct title, sender, and recipient in the Recipient's mailbox:

The name of the recipient you see is probably not what we passed in 管理员 , because many mail service providers will automatically replace the recipient name with the name of the user registration when displaying the message, but the display of the other Recipient's name is not Affected.

If we look at the original content of the email, we can see the following encoded Headers:

From: =?utf-8?b?UHl0aG9u54ix5aW96ICF?= <xxxxxx@163.com>To: =?utf-8?b?566h55CG5ZGY?= <xxxxxx@qq.com>Subject: =?utf-8?b?5p2l6IeqU01UUOeahOmXruWAmeKApuKApg==?=

This is the Header text that is encoded by the object, containing UTF-8 encoded information and BASE64 encoded Text. If we were to manually construct such coded text ourselves, It was obviously more complicated.

Send an HTML message

What if we want to send HTML messages instead of plain plain text files? The method is simple, when the object is constructed MIMEText , the HTML string is passed in, and then the second parameter plain is changed to html :

msg = MIMEText(‘<html><body><h1>Hello</h1>‘ + ‘<p>send by <a href="http://www.python.org">Python</a>...</p>‘ + ‘</body></html>‘, ‘html‘, ‘utf-8‘)

Send the message again, and you'll see the message displayed in Html:

Send Attachments

What if I add an attachment to an email? Messages with attachments can be viewed as messages that contain several parts: text and individual attachments, so you can construct an MIMEMultipart object that represents the message itself, and then add one as the body of the MIMEText message, and then continue to add the object that represents the attachment MIMEBase :

# mail Object: msg = Mimemultipart () msg[' From '] = _format_addr (U ' python lover <%s> '% from_addr) msg[' To '] = _format_addr (U ' admin <%s> '% to_addr) msg[' Subject ' = Header (U ' Greetings from SMTP ... ',' Utf-8 '). encode ()# The message body is MIMEText:msg.attach (mimetext (' Send with File ... ',' Plain ',' Utf-8 '))# Adding an attachment is to add a mimebase that reads a picture from the Local:with Open ( '/users/michael/downloads/test.png ',  RB ') as f: # set the MIME and file name of the attachment, here is the png type: MIME = mimebase (  ' image ',  ' png ', Filename= ' test.png ') # plus necessary header information: Mime.add_header ( ' content-disposition ',  ' attachment ', Filename= ' test.png ') mime.add_header ( ' Content-id ',  "<0>") mime.add_header ( ' x-attachment-id ',  0 ') # The contents of the attachment read in: mime.set_payload (f.read ()) # with Base64 code: Encoders.encode _base64 (mime) # added to MIMEMultipart:msg.attach (mime)      

then, as the normal send process msg (note the type has become MIMEMultipart ) sent out, you can receive the following message with Attachments:

Send picture

What do I do if I want to embed a picture in the message body? Link a picture address directly in an HTML Message. The answer is that most e-mail providers automatically block images with an outside chain because they don't know if the links are pointing to a malicious website.

To embed the image in the message body, we simply add the message as an attachment by sending it as an attachment, and then embed the attachment as a picture in the HTML by reference src="cid:0" . If you have multiple pictures, number them sequentially, and then reference the different cid:x .

Change the code added above to MIMEMultipart MIMEText plain html , and then refer to the picture in the appropriate location:

msg.attach(MIMEText(‘<html><body><h1>Hello</h1>‘ + ‘<p><img src="cid:0"></p>‘ + ‘</body></html>‘, ‘html‘, ‘utf-8‘))

Send again, you can see the image directly embedded in the message body effect:

Supports both HTML and plain formats

If we send an HTML message, the recipient will be able to browse the contents of the message through a browser or software such as outlook, but what if the recipient is using a device that is too old to view HTML mail?

By attaching a plain text while sending html, you can automatically downgrade to view plain text messages if the recipient cannot view the messages in HTML format.

You MIMEMultipart can combine an HTML and a plain, and be aware that specifying subtype is alternative :

msg = MIMEMultipart(‘alternative‘)msg[‘From‘] = ...msg[‘To‘] = ...msg[‘Subject‘] = ...msg.attach(MIMEText(‘hello‘, ‘plain‘, ‘utf-8‘))msg.attach(MIMEText(‘<html><body><h1>Hello</h1></body></html>‘, ‘html‘, ‘utf-8‘))# 正常发送msg对象...
Encrypt SMTP

When you use the standard 25 port to connect to an SMTP server, you use clear text transmission, and the entire process of sending the message may be Bugged. To send messages more securely, You can encrypt the SMTP session by creating an SSL secure connection before you send the message using the SMTP Protocol.

Some mail service providers, such as gmail, provide SMTP services that must be encrypted for Transmission. Let's take a look at how to send mail via secure SMTP provided by Gmail.

It must be known that the SMTP port of Gmail is 587, so the code is modified as Follows:

‘smtp.gmail.com‘smtp_port = 587server = smtplib.SMTP(smtp_server, smtp_port)server.starttls()# 剩下的代码和前面的一模一样:server.set_debuglevel(1)...

You only need to SMTP invoke the method immediately after the object is created, starttls() creating a secure Connection. The following code is exactly the same as the previous send message Code.

If you are unable to connect to Gmail's SMTP server because of network problems, please believe that our code is not a problem, you need to make necessary adjustments to your network settings.

Summary

Using Python's smtplib to send mail is very simple, as long as you have mastered the various types of message construction methods, correctly set the message header, you can send a smooth.

Constructs a mail object is an Messag object, if constructs an MIMEText object, represents a text mail object, if constructs an MIMEImage object, represents one as the attachment picture, wants to combine several objects together, uses MIMEMultipart the object, but MIMEBase can represent any object. Their inheritance relationships are as follows:

Message+- MIMEBase   +- MIMEMultipart   +- MIMENonMultipart      +- MIMEMessage      +- MIMEText      +- MIMEImage

This nesting relationship allows for the construction of arbitrarily complex messages. You can view the packages they are in and detailed usage through the Email.mime Documentation.

Source Code Reference:

Https://github.com/michaelliao/learn-python/tree/master/email

Transfer from Liaoche Liao

Http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/ 001386832745198026a685614e7462fb57dbf733cc9f3ad000

Python Send mail (go)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.