Python-Send mail (smtplib, email)

Source: Internet
Author: User
Tags sendfile email account

Send mail (smtplib, email)

Typically, after the API and UI Automation tests, you need to send the running test report to the specified mail group, which can be done using two modules from Python:

Smtplib module is mainly responsible for sending mail such as: Connect mailbox server, login mailbox, send mail

Email module is mainly responsible for the construction of mail such as: sender, Recipient, subject, text, attachments, pictures, HTML and so on.

First, Smtplib

1. smtplib Example:

Import smtplib# instantiates SMTP connection (IP, port) SMTP = Smtplib. Smtp_ssl (self. Smtp_server, 465)  # Connect the Mailbox server # Smtp.connect (self) using SSL secure encryption. Smtp_server, 465)           # Use Connect unsecured mode to connect to a Mailbox server # login (email account, password) smtp.login (self.username, Self.password) #发送邮件 (sender Mail, The recipient's mailbox/Multiple recipient mailboxes are separated by commas, and as_string () turns msg (Mimetext object or Mimemultipart object) to str) smtp.sendmail (Self.sender, "[Email Protected] ", msg.as_string ()) #关闭SMTP连接smtp. Quit ()

2, smtplib commonly used built-in functions:

Smtp.set_debuglevel (level): #设置是否为调试模式. The default is False,smtp.connect ([host[, Port]]): #连接到指定的smtp服务器. The parameters represent Smpt hosts and ports, respectively. # default is the 25 port of this machine. Can also be written in the form of Hostname:port. Smtp.docmd (cmd[, argstring]): #向smtp服务器发送指令. An optional parameter, argstring, represents the parameters of the directive. Smtp.helo ([hostname]): #使用 the "helo" directive confirms the identity to the server. The equivalent of telling the SMTP server "who I am". Smtp.has_extn (name): #判断指定名称在服务器邮件列表中是否存在. #出于安全考虑, the SMTP server tends to block the directive. Smtp.verify (address): #判断指定邮件地址是否在服务器中存在. #出于安全考虑, the SMTP server tends to block the directive. Smtp.login (user, password): #登陆到smtp服务器. Smtp.sendmail (self, from_addr, To_addrs, MSG, mail_options=[],             rcpt_options=[]): #发送邮件. Smtp.quit (): #断开与smtp服务器的连接, equivalent to sending a "quit" instruction.

Second, email

Email module has a MIME package, mime English is all called "Multipurpose Internet Mail Extensions", that is, multi-purpose Internet Mail extension, is the current Internet e-mail messages generally follow the technical specifications, MIME package commonly used built-in methods are as follows:

There are three types of Mimemultipart:

Mimemultipart (' mixed ') # Messages with a message type of "multipart/mixed" contain attachments. Up compatible, if a message has a plain text body, a hypertext body, an inline resource, and an attachment, select the mixed type. Mimemultipart (' related ') # message type "multipart/related" contains images, sounds, and other embedded resources in the body of the message. Mimemultipart (' alternative ') # Messages with a message type of "multipart/alternative" include plain text body (text/plain) and hypertext Body (text/html).

Mimetext: Used to process HTML text and text text in a message "Plain text body (text/plain) and hypertext Body (text/html)";

Mimeimage: Used to process picture pictures in a message

1. Build sender, Recipient, subject

From Email.mime.multipart import Mimemultipart from    email.mime.text import mimetext from    email.mime.image Import mimeimagemsg = Mimemultipart (' mixed ') msg[' Subject '] = "mail subject" msg[' from ' = ' sender mailbox ' msg[' to '] = ' recipient mailbox ' msg[' Date ']= ' 2012-3-16 '

Note:

Msg.add_header (_name,_value,**_params): Adds a message header field. Msg.as_string (): Is the MSG (Mimetext object or Mimemultipart object) into STR, if there is only one HTML hypertext body or plain ordinary text body, the type of general msg can be Mimetext If it is multiple, it is added to the mimemultipart,msg type and becomes Mimemultipart. Msg.attach (Mimetext object or Mimeimage object): Adds a Mimetext object or Mimeimage object to the Mimemultipart object. The Mimemultipart object represents the message itself, the Mimetext object or the Mimeimage object represents the message body, and it is popular to add text, HTML, attachments, and images to Mimemultipart (' mixed ').

2. Build text content

Text = "Test,test!!!"    Text_plain = Mimetext (text, ' Plain ', ' utf-8 ')    Msg.attach (Text_plain)    

3. Building HTML Content

html = "" "

4. Build picture Content

Sendimagefile=open (R ' E:\python\image.png ', ' RB '). Read () image = Mimeimage (sendimagefile) Image.add_header (' Content-id ', ' <image1> ') image["content-disposition"] = ' attachment; Filename= "Testimage.png" ' Msg.attach (image)

5, build the attachment content

From e-mail import encoderssendfile=open (R ' D:\pythontest\report--201805171734.html ', ' RB '). Read () Report = Email.mime.text.MIMEText (sendfile, ' html ', ' Utf-8 ') report["content-type"] = ' application/octet-stream ' report.add_ Header (' content-disposition ', ' attachment ', filename= (' GBK ', ' ', Report_name) ') encoders.encode_base64 (report) # The report is Base64 encoded Msg.attach (report)

Three, complete example

Python sends a message that contains text, HTML, pictures, attachments:

Import smtplibfrom email.mime.multipart import mimemultipartfrom email.mime.text import Mimetextfrom email.mime.image Import mimeimagefrom Email Import encoders# Set the required parameters for Smtplib # below the sender, the recipient is for message transfer. SmtpServer = ' SMTP server IP ' username = ' mailbox account ' password= ' mailbox password ' sender= ' sender mailbox ' #receiver = ' [email protected] ' # Recipients are multiple recipients receiver=[' [email protected] ', ' [email protected] '] #下面的主题, sender, recipient, date is displayed on the Mail page. msg = Mimemultipart (' mixed ') msg[' Subject '] = "mail test" msg[' from ' = ' sender mailbox ' #msg [' to '] = ' [email protected] ' # The recipient is a number of recipients, and the list is converted to A; interval string msg[' to ' = ";" Through a join. Join (receiver) #msg [' Date ']= ' 2012-3-16 ' #构造文字内容text = ' test,test!!! ' Text_plain = Mimetext (text, ' Plain ', ' utf-8 ') Msg.attach (text_plain) #构造图片链接sendimagefile =open (' E:\python\image.png ') , ' RB '). Read () image = Mimeimage (sendimagefile) image.add_header (' Content-id ', ' <image1> ') image[" Content-disposition "] = ' attachment; Filename= "Testimage.png" ' Msg.attach (image) #构造htmlhtml = "" "

  

Python-Send mail (smtplib, email)

Related Article

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.