Python Learning (16)-send emails with scripts

Source: Internet
Author: User
Tags imap rfc

Traditional mail Transmission protocols include SMTP, POP3, and IMAP:
SMTP (Simple Mail Transfer Protocol) The Mail Transfer Agent (MTA) program uses the SMTP protocol to send an email to the recipient's mail server. The SMTP protocol can only be used to send mails and cannot be used to receive mails. Most email sending servers use the SMTP protocol. The default TCP port number of SMTP protocol is 25.
An important feature of the SMTP protocol is its ability to transmit mails through relay. It works in two situations: one is the transmission of email from the client to the server, and the other is the transmission from one server to another.
The Post Office Protocol protocol provides users with a simple and standard way to access and obtain emails. The mail client that uses POP3 Protocol Usually works in the process of connecting to the server, getting all information and saving it on the user host, deleting the messages from the server, and then disconnecting. The default TCP port number for POP3 is 110.
The IMAP (Internet Message Access Protocol) Protocol also provides a convenient Mail Download service, allowing users to read offline. The email client that uses the IMAP Protocol usually keeps the information on the server until the user explicitly deletes it. This feature allows multiple clients to manage one mailbox at a time. The IMAP Protocol provides the abstract browsing function, allowing users to determine whether to download after reading the arrival time, topic, sender, size, and other information of all emails. The default TCP port number of the IMAP protocol is 143.
In addition, for the requirements on the mail format, refer to the standard rfc2822 and RFC 1341:
Each mail has two parts: the mail header and the mail Body, which are separated by a blank line. Each field in the mail header consists of two parts: field name and field value, which are separated by colons. Note the following two fields: From and sender. The from field specifies the sender of the email, and the sender field specifies the sender of the email. If the from field contains more than one author, you must specify the sender field. If the from field has only one author and the author is the same as the sender, you should not use the sender field, otherwise, use both the from field and the sender field.
The mail body contains the content of the mail. Its type is specified by the Content-Type field in the mail header. In the mail format defined in RFC 2822, the mail body is only a string of ASCII characters. Mime extended Message format. It is used to support non-ASCII text, non-text attachments, and multi-part body.

Module Introduction
In python, The smtplib and email modules for mail sending are described in two modules:
1. smtplib Module
Smtplib. SMTP ([host [, Port [, local_hostname [, timeout])
SMTP constructor indicates a connection with the SMTP server. Through this connection, you can send commands to the SMTP server to execute relevant operations (such as login and email sending ). All parameters are optional.
HOST: SMTP server host name
Port: the SMTP service port. The default value is 25. If the two parameters are provided when an SMTP object is created, the connect method is automatically called during initialization to connect to the server.
The smtplib module also provides smtp_ssl and LMTP classes, which are basically the same as SMTP.
Methods provided by smtplib. SMTP:
SMTP. set_debuglevel (level): sets whether the debug mode is used. The default value is false, that is, non-debug mode, indicating that no debugging information is output.
SMTP. Connect ([host [, port]): connect to the specified SMTP server. The parameters represent the smpt host and port respectively.
Smtp.doc MD (CMD [, argstring]): sends commands to the SMTP server. The optional parameter argstring indicates the command parameter.
SMTP. Helo ([hostname]): use the "HELO" command to confirm the identity of the server. It is equivalent to telling the SMTP server "who I am ".
SMTP. has_extn (name): determines whether the specified name exists in the server email list. For security reasons, SMTP servers often block this command.
SMTP. Verify (address): determines whether the specified email address exists on the server. For security reasons, SMTP servers often block this command.
SMTP. login (user, password): log on to the SMTP server. Currently, almost all SMTP servers must verify that the user information is valid before sending emails.
SMTP. Sendmail (from_addr, to_addrs, MSG [, mail_options, rcpt_options]): send an email. Note that the third parameter, MSG is a string, indicating the mail. We know that an email generally consists of the title, sender, recipient, email content, attachments, etc. When sending an email, pay attention to the MSG Format. This format is defined in the SMTP protocol.
SMTP. Quit (): disconnect from the SMTP server, which is equivalent to sending the "quit" command.
2. Email Module
Class email. Mime. Base. mimebase (_ maintype, _ subtype, ** _ Params): This is a base class of mime. Generally, you do not need to create an instance when using it. Among them, _ maintype is the 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 [, _ Params]: A subclass of mimebase, a set of multiple MIME objects. The default value of _ subtype is mixed. Boundary is the boundary of the mimemultipart. The default boundary is only a handful.
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])

Class email. mime. text. mimetext (_ text [, _ subtype [, _ charset]): MIME Text object, where _ text is the mail content and _ subtype is the mail type, it can be text/plain (plain text mail), HTML/plain (HTML mail), _ charset encoding, or gb2312.


Sample Code:

#! /Usr/bin/ENV python3 # Coding: UTF-8 import smtplib from email. mime. text import mimetext from email. header import header sender = '*** 'sender ER =' *** '# The sender er can also be a list of sent mailboxes, sendmail sends an email to subject = 'python email test' smtpserver = 'smtp .163.com 'username =' *** 'password = '*** 'msg = mimetext ('', 'text', 'utf-8') # The parameter 'utf-8' is required for Chinese characters. single-byte characters do not require MSG ['subobject'] = header (subject, 'utf-8') SMTP = smtplib. SMTP () SMTP. connect ('smtp .163.com ') SMTP. login (username, password) SMTP. sendmail (sender, receiver, MSG. as_string () SMTP. quit ()

You can also send emails with attachments:

#! /Usr/bin/ENV python3 # Coding: UTF-8 import smtplib from email. mime. multipart import mimemultipart from email. mime. text import mimetext from email. mime. image import mimeimage sender = '*** 'caller =' *** 'subject = 'python email test' smtpserver = 'smtp .163.com 'username =' *** 'password =' * ** 'msgroot = mimemultipart ('related ') msgroot ['subobject'] = 'test message' # construct the attachment ATT = mimetext (open ('H: \ Python \ 1.jpg ', 'rb '). read (), 'base64', 'utf-8 ') ATT ["Content-Type"] = 'application/octet-stream' ATT ["content-disposition"] = 'attachment; filename = "1.jpg" 'msgroot. attach (ATT) SMTP = smtplib. SMTP () SMTP. connect ('smtp .163.com ') SMTP. login (username, password) SMTP. sendmail (sender, aggreger, msgroot. as_string () SMTP. quit ()

ZZ: http://blog.csdn.net/bravezhe/article/details/7659173

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.