Python Send mail

Source: Internet
Author: User
Tags base64

First, the relevant module introduction

Send mail mainly use smtplib and email two modules, here first on two modules for a brief introduction:
1. Smtplib Module

Smtplib. SMTP ([host[, port[, local_hostname[, timeout]])

The SMTP class constructor, which represents the connection to the SMTP server, enables you to send instructions to the SMTP server to perform related operations such as logging in and sending mail. All parameters are optional.

HOST:SMTP Server Host Name

The port of the PORT:SMTP service is 25 by default, and when the SMTP object is created, the Connect method is automatically called to connect to the server at initialization time.

The Smtplib module also provides the Smtp_ssl class and the Lmtp class, and their operation is basically consistent with SMTP.

  Smtplib. Methods that are provided by SMTP:

Smtp.set_debuglevel (level): Sets whether to debug mode. The default is false, which is non-debug mode, which means that no debug information is output.

Smtp.connect ([host[, Port]]): Connect to the specified SMTP server. The parameters represent Smpt hosts and ports, respectively. Note: You can also specify the port number (for example: SMPT.YEAH.NET:25) in the host parameter, so there is no need to give the port parameter.

Smtp.docmd (cmd[, argstring]): Sends instructions to the SMTP server. An optional parameter, argstring, represents the parameters of the directive.

Smtp.helo ([hostname]): Use the "helo" directive to confirm the identity to the server. The equivalent of telling the SMTP server "who I am".

Smtp.has_extn (name): Determines whether the specified name exists in the server mailing list. For security reasons, the SMTP server often blocks the directive.

Smtp.verify: Determines whether the specified e-mail address exists on the server. For security reasons, the SMTP server often blocks the directive.

Smtp.login (user, password): Log on to the SMTP server. Almost all SMTP servers now have to allow messages to be sent after verifying that the user information is legitimate.

Smtp.sendmail (From_addr, To_addrs, msg[, Mail_options, rcpt_options]): Send mail. 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.

Smtp.quit (): Disconnects from the SMTP server, which is equivalent to sending a "quit" instruction. (many programs are used in the Smtp.close (), specific and quit the difference between Google a bit, also did not find the answer. )

2. Email module

The Emial module is used to process mail messages, including MIME and other RFC 2822-based message documents. Using these modules to define the contents of the message is very simple. The classes it includes are (in more detail, visible: http://docs.python.org/library/email.mime.html):

Class Email.mime.base.MIMEBase (_maintype, _subtype, **_params): This is a base class for mime. You generally do not need to create an instance when you use it. Where _maintype is a content type, such as text or image. _subtype is the minor type of the content, such as plain or GIF. **_params is a dictionary that is passed directly to Message.add_header ().

Class Email.mime.multipart.MIMEMultipart ([_subtype[, boundary[, _subparts[, a subclass of _params]]]]:mimebase, a collection of multiple MIME objects, The _subtype default value is mixed. Boundary is the boundary of the Mimemultipart, and the default boundary is a number.

Class Email.mime.application.MIMEApplication (_data[, _subtype[, _encoder[, **_params]]): A subclass of Mimemultipart.

Class Email.mime.audio. Mimeaudio (_audiodata[, _subtype[, _encoder[, **_params]]): MIME Audio Object

Class Email.mime.image.MIMEImage (_imagedata[, _subtype[, _encoder[, **_params]]): MIME binary file object.

Class Email.mime.message.MIMEMessage (_msg[, _subtype]): A specific message instance, using the following method:

  

Msg=mail. Message.message ()    #一个实例 msg[' to ']= ' [email protected] '      #收件人 msg[' from ']= ' [email protected] '       #发件人 msg[' Date ']= ' 2018-1-19 '           #时间日期 (can be automatically added without writing) msg[' subject ']= ' Sub '    

Ii. the specific implementation code of various mails

1. Ordinary text mail

Import smtplib #用来操作smtp服务器from email.mime.text import mimetext #用来操作邮件content = "" Python e-    mail is simple ~ "" "Sendstr =" "" [ Email protected], "" "Sendlist = Sendstr.replace (" \ n "," "). Split (", ") #发送人列表msg = mimetext (content," plain "," Utf-8 ") # Message header msg["Subject" = "Friday benefit" msg["from"] = "[email protected]" msg["to"] = sendstr# Configure SMTP Service server = Smtplib. Smtp_ssl ("smtp.qq.com", 465) server.login ("987**** @qq. com", "******") #邮箱SMTP密码, such as: Uwcyaduiyxaabhdgserver.sendmail ( "987**** @qq. com", sendlist,msg.as_string ()) Server.quit ()

      2, messages with attachments, HTML, pictures

Import smtplibfrom email.mime.multipart import mimemultipartfrom email.mime.text Import mimetextmsg = Mimemultipart (' Related ') msg["Subject" = "Mail Subject" # msg["from"] = "987*** @qq. com" msg["to"] = addresseemsg["Cc"] = ACC #抄送 # body Content Text = Mimetex T (U ' message body!) ', ' plain ', ' utf-8 ') Msg.attach (text) #附件1 # Read the XLS file as an attachment, open () to take the parameter ' RB ', so that the file becomes binary format, so that the ' base64 ' encoding works, otherwise the attachment opens garbled # ATT = Mimetext (Open (' C:\\ceshi.xls ', ' RB '). Read (), ' base64 ', ' GB2312 ') # att[' content-type '] = ' application/vnd.ms-excel ' # A tt[' content-disposition '] = ' attachment; filename = "1.xls" ' #读取xlsx文件作为附件, open () to take the parameter ' RB ', to make the file into binary format, so that the ' base64 ' encoding works, otherwise the attachment opens garbled att = mimetext (open (U '%s.xlsx '% ' filename ', ' RB '). Read (), ' base64 ', ' utf-8 ') att[' content-type '] = ' application/ Vnd.openxmlformats-officedocument.spreadsheetml.sheet ' # under the filename equals sign (=) does not seem to have a space after att[' content-disposition ' = ' Attachment filename = "%s.xlsx" '% ' filename ' Msg.attach (att) #附件2att2 = mimetext (open (' d:\\123.txt ', ' RB '). Read (), ' base64 ', ' gb2312 ') att2["content-type"] = ' ApplicatiOn/octet-stream ' att2["content-disposition"] = ' attachment; Filename= "123.txt" ' Msg.attach (att2) #HTMLcontent = "<p><a href= ' http://www.baidu.com ' > Baidu </a> a bit </p> "HTMLText = Mimetext (content,_subtype= ' HTML ', _charset= ' Utf-8 ') Msg.attach (htmltext) #图片file1 =" c:\\ Hello.jpg "image = Mimeimage (open (File1, ' RB '). Read ()) Image.add_header (' Content-id ', ' <image1> ') Msg.attach ( image) #有搜集来的带图片的HTMLmsgText = Mimetext (' <b>some <i>HTML</i> text</b> and an image.good! ', ' html ', ' Utf-8 ') Msg.attach (Msgtext) #配置SMTP服务, here with QQ mailbox Server = Smtplib. Smtp_ssl ("smtp.qq.com", 465) #如果是其他邮箱可以直接换: #server = smtplib. SMTP () #server. Connect (' SMTP. XXX.com ') server.login ("987*** @qq. com", "need to go to mailbox to turn on SMTP service write password here") Server.sendmail ("987*** @qq. com", addressee, Msg.as_ String ()) #发送给多人, simultaneously copied to many people, sender and cc person placed in the same list #server.sendmail (sender, Addressee.split (', ') + acc.split (', '), Msg.as_ String ()) Server.quit ()

  

  

  

  



Python 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.