The main way Python sends various types of 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 ']= ' 2012-3-16 '
msg[' subject ']= ' Hello World '

Class Email.mime.text.MIMEText (_text[, _subtype[, _charset]): Mime text object, where _text is the message content, _subtype message type, can be text/ Plain (plain text mail), Html/plain (HTML mail), _charset encoding, can be gb2312 and so on.

Ii. specific implementation codes for several types of mails

1. Ordinary text mail

The key to the implementation of plain text mail delivery is to set _subtype in Mimetext to plain. First, smtplib and Mimetext are imported. Create SMTPLIB.SMTP instance, connect mail SMTP server, send after login, specific code is as follows: (implemented under python2.6)

#-*-Coding:utf-8-*-
‘‘‘
Send txt text message
Little Five righteousness: Http://www.cnblogs.com/xiaowuyi
‘‘‘
Import Smtplib
From Email.mime.text import Mimetext
mailto_list=[[email protected]]
Mail_host= "SMTP. XXX.com "#设置服务器
Mail_user= "XXXX" #用户名
mail_pass= "XXXXXX" #口令
mail_postfix= "xxx.com" #发件箱的后缀

def send_mail (to_list,sub,content):
Me= "Hello" + "<" +mail_user+ "@" +mail_postfix+ ">"
msg = Mimetext (content,_subtype= ' plain ', _charset= ' gb2312 ')
msg[' Subject ' = Sub
Msg[' from '] = Me
Msg[' to '] = ";". Join (To_list)
Try
Server = Smtplib. SMTP ()
Server.connect (Mail_host)
Server.login (Mail_user,mail_pass)
Server.sendmail (Me, To_list, msg.as_string ())
Server.close ()
Return True
Except Exception, E:
Print str (e)
Return False
if __name__ = = ' __main__ ':
If Send_mail (mailto_list, "Hello", "Hello world! "):
Print "Sent successfully"
Else
Print "Send Failed"

2. Sending HTML messages

Unlike text messages, the _subtype in Mimetext is set to HTML. The specific code is as follows: (python2.6 implementation)

#-*-Coding:utf-8-*-
‘‘‘
Send an HTML text message
Little Five righteousness: Http://www.cnblogs.com/xiaowuyi
‘‘‘
Import Smtplib
From Email.mime.text import Mimetext
mailto_list=["[email protected]"]
Mail_host= "SMTP. XXX.com "#设置服务器
Mail_user= "XXX" #用户名
mail_pass= "XXXX" #口令
mail_postfix= "xxx.com" #发件箱的后缀

def send_mail (to_list,sub,content): #to_list: Recipient; sub: subject; Content: Message contents
Me= "Hello" + "<" +mail_user+ "@" +mail_postfix+ ">" #这里的hello可以任意设置, after receiving the letter, will be displayed according to the settings
msg = Mimetext (content,_subtype= ' HTML ', _charset= ' gb2312 ') #创建一个实例, this is set to HTML format mail
msg[' Subject ' = Sub #设置主题
Msg[' from '] = Me
Msg[' to '] = ";". Join (To_list)
Try
s = smtplib. SMTP ()
S.connect (mail_host) #连接smtp服务器
S.login (Mail_user,mail_pass) #登陆服务器
S.sendmail (Me, To_list, msg.as_string ()) #发送邮件
S.close ()
Return True
Except Exception, E:
Print str (e)
Return False
if __name__ = = ' __main__ ':
If Send_mail (mailto_list, "Hello", "<a href= ' Http://www.cnblogs.com/xiaowuyi ' > Xiao Wu yi </a>"):
Print "Sent successfully"
Else
Print "Send Failed"

3. Send mail with Attachments

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

#-*-coding:cp936-*-
‘‘‘
Send message with attachment
Little Five righteousness: Http://www.cnblogs.com/xiaowuyi
‘‘‘

From Email.mime.text import Mimetext
From Email.mime.multipart import Mimemultipart
Import Smtplib

#创建一个带附件的实例
msg = Mimemultipart ()

#构造附件1
ATT1 = Mimetext (open (' D:\\123.rar ', ' RB '). Read (), ' base64 ', ' gb2312 ')
att1["Content-type"] = ' application/octet-stream '
att1["content-disposition"] = ' attachment; Filename= "123.doc" #这里的filename可以任意写, what name to write, what name is displayed in the message
Msg.attach (ATT1)

#构造附件2
ATT2 = 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)

#加邮件头
Msg[' to '] = ' [email protected] '
Msg[' from '] = ' [email protected] '
msg[' subject ' = ' Hello World '
#发送邮件
Try
Server = Smtplib. SMTP ()
Server.connect (' SMTP. XXX.com ')
Server.login (' XXX ', ' XXXXX ') #XXX为用户名, XXXXX for password
Server.sendmail (msg[' from '], msg[' to '],msg.as_string ())
Server.quit ()
print ' Send Success '
Except Exception, E:
Print str (e)

4. Send pictures using Mimeimage

#-*-coding:cp936-*-
Import Smtplib
Import Mimetypes
From Email.mime.text import Mimetext
From Email.mime.multipart import Mimemultipart
From Email.mime.image import Mimeimage

Def autosendmail ():
msg = Mimemultipart ()
Msg[' from '] = "[Email protected]"
msg[' to ' = "[email protected]"
msg[' Subject ' = "Hello World"


txt = Mimetext ("This is Chinese mail content oh", ' plain ', ' gb2312 ')
Msg.attach (TXT)


file1 = "C:\\hello.jpg"
Image = Mimeimage (open (File1, ' RB '). Read ())
Image.add_header (' Content-id ', ' <image1> ')
Msg.attach (image)


Server = Smtplib. SMTP ()
Server.connect (' SMTP. XXX.com ')
Server.login (' XXX ', ' XXXXXX ')
Server.sendmail (msg[' from '],msg[' to '],msg.as_string ())
Server.quit ()

if __name__ = = "__main__":
Autosendmail ()

The use of mimeimage to send pictures, originally wanted to picture can be displayed in the body, but the code after the run found, is still sent as an attachment, I hope to have a master can point out, how can send in the body of the picture displayed in the message, is the picture is an attachment exists, but at the same time can be displayed in the body, Specific forms such as.

The main way Python sends various types of mail

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.