Python3 smtp Send mail

Source: Internet
Author: User
Tags base64

The SMTP (Simple Mail Transfer Protocol) is simply the message Transfer Protocol, which is a set of rules for sending mail from the source address to the destination, and it controls the way the letters are relayed.

Python's Smtplib provides a convenient way to send e-mails. It provides a simple encapsulation of the SMTP protocol.

Python creates SMTP object syntax as follows:

Import smtplibsmtpobj = Smtplib. SMTP ([host [, Port [, Local_hostname]])

Parameter description:

    • HOST:SMTP Server host. You can specify the IP address of the host or the domain name such as: w3cschool.cn, which is an optional parameter.
    • PORT: If you provide the host parameter, you need to specify the port number that the SMTP service uses, and the SMTP port number is typically 25.
    • Local_hostname: If SMTP is on your local computer, you only need to specify the server address as localhost.

The Python SMTP object uses the SendMail method to send the message with the following syntax:

Smtp.sendmail (From_addr, To_addrs, msg[, Mail_options, Rcpt_options]

Parameter description:

    • From_addr: Mail Sender address.
    • To_addrs: String list, mailing address.
    • Msg: Send Message

Notice here that the third parameter, MSG, is a string that represents the message. We know that the mail is generally composed of the title, sender, recipient, mail content, attachments, etc., when sending mail, pay attention to the format of MSG. This format is the format defined in the SMTP protocol.

Instance

Here's a simple example of sending a message using Python:

#!/usr/bin/python3import smtplibfrom email.mime.text Import mimetextfrom email.header Import headersender = ' [email Protected] ' receivers = [' [email protected] ']  # receive mail, can be set as your QQ mailbox or other mailbox # three parameters: the first text content, the second plain text format, the third Utf-8 Set Encoding message = Mimetext (' Python Mail send Test ... ', ' plain ', ' utf-8 ') message[' from ' = Header ("W3cschool tutorial", ' Utf-8 ') message[' To '] =  header ("Test", ' utf-8 ') Subject = ' Python SMTP mail test ' message[' subject '] = header (subject, ' Utf-8 ') Try:    Smtpobj = Smtplib. SMTP (' localhost ')    smtpobj.sendmail (sender, Receivers, message.as_string ())    print ("Mail sent successfully") except Smtplib. Smtpexception:    Print ("Error: Unable to send mail")

We use three quotation marks to set up the mail message, the standard message needs three header information: from, to, and Subject , each message is directly separated by a blank line.

We connect to SMTP access by instantiating the SMTP object smtpobj of the Smtplib module and use the sendmail method to send the information.

Execute the above procedure, if you install SendMail on the machine, it will output:

$ python3 test.py Message sent successfully

Check out our inbox (usually in the trash) to see the email message:

If we do not have sendmail access to this machine, we can also use the SMTP access of other service providers (QQ, NetEase, Google, etc.).

#!/usr/bin/python3import smtplibfrom email.mime.text Import mimetextfrom email.header import header# third-party SMTP service Mail_ Host= "SMTP. xxx.com "  #设置服务器mail_user =" XXXX "    #用户名mail_pass =" XXXXXX "   #口令 sender = ' [email protected] ' receivers = [' [ Email protected]  # receive mail, can be set to your QQ mailbox or other mailbox message = Mimetext (' Python Mail send Test ... ', ' plain ', ' utf-8 ') message[' from '] = Header ("W3cschool tutorial", ' Utf-8 ') message[' to ' =  header ("Test", ' utf-8 ') Subject = ' Python SMTP mail test ' message[' subject ' ] = Header (subject, ' Utf-8 ') Try:    smtpobj = Smtplib. SMTP ()     smtpobj.connect (mail_host)    # 25 is the SMTP port number    Smtpobj.login (mail_user,mail_pass)    Smtpobj.sendmail (sender, Receivers, message.as_string ())    print ("message sent successfully") except Smtplib. Smtpexception:    Print ("Error: Unable to send mail")
Use Python to send HTML-formatted messages

Python sends HTML-formatted messages differently than messages that send plain text messages by setting _subtype in Mimetext to HTML. The specific code is as follows:

#!/usr/bin/python3import smtplibfrom email.mime.text Import mimetextfrom email.header Import headersender = ' [email Protected] ' receivers = [' [email protected] ']  # receive mail, can be set to your QQ mailbox or other mailbox mail_msg = "" <p>python Mail send test ... </p ><p><a href= "http://www.w3cschool.cn" > This is a link </a></p> "" message = Mimetext (Mail_msg, ' html ', ' Utf-8 ') message[' from ' = Header ("W3cschool tutorial", ' Utf-8 ') message[' to '] =  header ("Test", ' utf-8 ') Subject = ' Python SMTP Mail test ' message[' Subject ' = Header (Subject, ' Utf-8 ') Try:    smtpobj = Smtplib. SMTP (' localhost ')    smtpobj.sendmail (sender, Receivers, message.as_string ())    print ("Mail sent successfully") except Smtplib. Smtpexception:    Print ("Error: Unable to send mail")

Execute the above procedure, if you install SendMail on the machine, it will output:

$ python3 test.py Message sent successfully

Check out our inbox (usually in the trash) to see the email message:

Python sends a message with an attachment

Send a message with an attachment, first create an instance of Mimemultipart (), and then construct the attachment, which, if there are multiple attachments, can be constructed in sequence and then sent using SMTPLIB.SMTP.

#!/usr/bin/python3import smtplibfrom email.mime.text Import mimetextfrom email.mime.multipart Import Mimemultipartfrom email.header Import headersender = ' [email protected] ' receivers = [' [email protected] '] # Receive mail, can be set to your QQ mailbox or other mailbox # Create an instance with attachments message = Mimemultipart () message[' from '] = Header ("W3cschool tutorial", ' Utf-8 ') message[' To '] = header ("Test", ' utf-8 ') Subject = ' Python SMTP mail test ' message[' subject '] = header (subject, ' Utf-8 ') #邮件正文内容message. Atta CH (mimetext (' This is W3cschool tutorial python mail send Test ... ', ' plain ', ' utf-8 ') # constructs attachment 1, transfers the Test.txt file under the current directory ATT1 = mimetext (Open (' Test.txt ', ' RB '). Read (), ' base64 ', ' Utf-8 ') att1["content-type"] = ' application/octet-stream ' # filename here can be arbitrarily written, what name to write , what name is displayed in the message att1["content-disposition"] = ' attachment; Filename= "Test.txt" ' Message.attach (ATT1) # construct attachment 2, transfer w3cschool.txt file under current directory ATT2 = mimetext (open (' w3cschool.txt ', ' RB ') . Read (), ' base64 ', ' Utf-8 ') att2["content-type"] = ' application/octet-stream ' att2[' content-disposition '] = ' Attachment Filename= "W3cschool.txt" ' MessAge.attach (att2) try:smtpobj = Smtplib. SMTP (' localhost ') smtpobj.sendmail (sender, Receivers, message.as_string ()) print ("Mail sent successfully") except Smtplib. Smtpexception:print ("Error: Unable to send mail")
$ python3 test.py Message sent successfully

Check out our inbox (usually in the trash) to see the email message:

Add a picture to HTML text

In the HTML text of the message, it is not valid to add an outer chain to the general mail Service provider, and the instance of the correct add breakout is as follows:

#!/usr/bin/python3import smtplibfrom email.mime.image Import mimeimagefrom email.mime.multipart Import Mimemultipartfrom email.mime.text Import mimetextfrom email.header Import headersender = ' [email protected] ' receivers = [' [email protected] '] # receive mail, can be set to your QQ mailbox or other mailbox Msgroot = Mimemultipart (' related ') msgroot[' from '] = Header ("W3cschool tutorial", ' Utf-8 ') msgroot[' to ' = Header ("Test", ' utf-8 ') Subject = ' Python SMTP mail test ' msgroot[' subject '] = Head ER (subject, ' utf-8 ') msgalternative = Mimemultipart (' alternative ') Msgroot.attach (msgalternative) mail_msg = "" "<p >python Mail Send test ... </p><p><a href= "http://www.w3cschool.cn" >w3cschool Tutorial links </a></p> <p> Photo Demo: </p><p></p> "" "Msgalternative.attach (Mimetext (Mail_ MSG, ' HTML ', ' Utf-8 ') # Specifies the picture as the current directory fp = open (' test.png ', ' RB ') Msgimage = Mimeimage (Fp.read ()) Fp.close () # defines the image ID, which is cited in the HTML text With Msgimage.add_header (' Content-id ', ' <image1> ') Msgroot.attach (msgimage) Try:smtpobj = Smtplib. SMTP (' localhost ') smtpobj.sendmail (sender, Receivers, msgroot.as_string ()) print ("Mail sent successfully") except Smtplib. Smtpexception:print ("Error: Unable to send mail")
$ python3 test.py Message sent successfully

View our Inbox (if the trash may need to be moved to your Inbox to display properly), you can view the message information:

Python3 smtp Send mail

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.