Python Send mail script

Source: Internet
Author: User
Tags time and date

Introduction to related modules

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 ()#an instancemsg[' to']='[email protected]'      #Where to sendmsg[' from']='[email protected]'       #your e-mail addressmsg['Date']='2012-3-16'           #Time and datemsg['subject']='Hello World'    #Message Subject

Simple to use

ImportSmtplib fromEmail.mime.textImportMimetext mail_host="xxx.xxx.com"  #setting up the serverMail_user="[email protected]"    #User namemail_pass="xxxxxx"   #Passwordmail_postfix="xxxx.com"  #outgoing outbox suffix  defSend_mail (to_list,sub,content): Me='%s<%[email protected]%s>'% (Sub,'xxxx', Mail_postfix) msg= Mimetext (content,_subtype='Plain', _charset='UTF-8') 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 ()returnTrueexceptException, E:PrintStr (e)returnFalseif __name__=='__main__': Emails=['[email protected]']#Target Mailbox    ifSend_mail (Emails,"Mail Test","Mail test! Mail test!"):          Print "sent successfully"      Else:          Print "Send failed"

Python Send mail script

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.