Python3 sending mail using smtplib and email modules

Source: Internet
Author: User
Tags base64 imap rfc all mail

SMTP (simple Mail Transfer Protocol)
The mail delivery Agent (mail Transfer Agent,mta) program uses the SMTP protocol to send email to the Recipient's mail server. The SMTP protocol can only be used to send messages and cannot be used to receive Messages. Most mail-sending servers (outgoing mail server) use the SMTP Protocol. The default TCP port number for the SMTP protocol is 25.

An important feature of the SMTP protocol is its ability to relay Messages. It works in two cases: one is the transfer of e-mail from the client to the server, and the other from one server to Another.

POP3 (Post Office Protocol) & IMAP (Internet Message Access Protocol)
The POP protocol and the IMAP protocol are the two most common protocols used for mail Reception. These two protocols are supported by almost all mail clients and Servers.
The POP3 protocol provides users with a simple, standard way to access mailboxes and get E-mail. E-mail clients that use the POP3 protocol typically work by connecting to the server, getting all the information, and saving the messages on the User's host, removing them from the server, and then disconnecting Them. The default TCP port number for the POP3 protocol is 110.

The IMAP protocol also provides a convenient e-mail download service that allows users to read Offline. E-mail clients that use the IMAP protocol usually keep 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 a summary browsing feature that allows users to decide whether to download after reading all the message arrival time, subject, sender, size, and so On. The default TCP port number for the IMAP protocol is 143.

Message Format (RFC 2822)
Each message has two Parts: a message header and a message body, separated by a blank line.
Message headers Each field contains two parts: a field name and a field value, separated by a Colon. There are two fields to be aware of: the From and sender FIELDS. The From field indicates the author of the message, and the sender field indicates the sender of the Message. If the From field contains more than one author, the sender field must be specified, and if the From field has only one author and the author and sender are the same, then the sender field should not be used, otherwise the From field and sender field should be used Simultaneously.
The message body contains the contents of the message, and its type is indicated by the Content-type field of the message header. In the message format defined by RFC 2822, The message body is simply a sequence of ascii-encoded Characters.
MIME (multipurpose Internet Mail Extensions) (RFC 1341)

MIME extends the format of messages to support NON-ASCII encoded text, Non-text attachments, and message bodies that contain multiple parts (multi-part).

Python Email Module

1. Class Email.message.Message
__getitem__,__setitem__ implement obj[key] form of Access.
Msg.attach (playload): adds playload to the current Msg.
Msg.set_playload (playload): Sets the message body of the whole MSG object to Playload.

Msg.add_header (_name, _value, **_params): adds a message header Field.

2. Class Email.mime.base.MIMEBase (_maintype, _subtype, **_params)

The base class for all MIME classes, which is a subclass of the Email.message.Message class.

3. Class Email.mime.multipart.MIMEMultipart ()

In the 3.0 version of the email module (Python 2.3-python 2.5), This class is located in Email. Mimemultipart.mimemultipart.

This class is a direct subclass of mimebase, which is used to generate MIME objects that contain multiple parts of the message Body.

4. Class Email.mime.text.MIMEText (_text)

Use the string _text to generate the body text of the MIME Object.


1. Email Code example:

# -*- coding:utf-8 -*-import osimport smtplibfrom email.mime.multipart  import mimemultipartfrom email.mime.base import mimebasefrom email.mime.text  Import mimetextfrom email.utils import commaspace,formatdatefrom email import  encoders#server[' name '], server[' user '], server[' passwd ']def send_mail (server, fro,  to, subject= "",  text= "",  files=[]):     assert type (server)   == dict    assert type (to)  == list    assert  Type (files)  == list    msg = mimemultipart ()      Msg[' from '] = fro                 #  note: The sender of the message (this is not the real sender, is the sender who received the message, what do you think??). )     msg[' Subject '] = subject         #  Mail subject     msg[' to '] =  Commaspace.join (to)   # commaspace== ',  '   recipients can be multiple, to is a list     msg[' Date '] = formatdate (localtime=true)  #  send time, when not set, using Outlook to receive mail will not show the date, QQ Web mailbox will show the dates      # mimimetext has three parameters: the first is text content, the second  plain  sets the text format, the third  utf-8  sets the encoding, and two and three can be omitted without writing     msg.attach (mimetext (text, ' plain ', ' utf-8 '))     for file  in files:          #  Add attachments can be multiple, files is a list, can be empty         part = mimebase (' application ',  ' Octet-stream ')  # ' Octet-stream ':  binary data        with open ( file, ' RB ')  as f:            part.set_ Payload (f.read ())    &NBSp;    encoders.encode_base64 (part)          Part.add_header (' content-disposition ',  ' attachment; filename= "%s" '  % os.path.basename (file ))         msg.attach (part)     smtp =  Smtplib. SMTP ()     # smtp = smtplib. Smtp_ssl ()   #  use SSL to log in (for example, QQ mailbox, Port is 465)     smtp.connect (server[' name ')  # connect has two parameters, the first is the mail server, the second is the port, and the default is 25    smtp.login (server[' user '], server [' passwd '])  #  username, password     smtp.sendmail (fro, to, msg.as_string ())  #  sender, recipient, Send Message (the sender and recipient here are the real senders and Recipients)     smtp.close ()   #  close Connection text =  ' '      hehe     ceshi ' ' send_mail ({' name ': ' xxx ', ' user ': ' oooo ', ' passwd ': ' Xxxooo '},           ' xxx ',           [' xo ', ' ox '],            ' hehe ',           Text,)

SMTP = Smtplib. SMTP ()

Smtp.connect (server[' name ')

These two sentences can also be written

SMTP = Smtplib. SMTP (server[' name '])


Msg[from] Since this is not the real sender, can it be used to forge messages and send spam??

The answer is yes, can be used to forge mail and send spam, only need to modify this msg[from] can


The SMTP object uses the SendMail method to send the message with the following syntax:

Smtp.sendmail (from_addr, to_addrs, msg[, mail_options, rcpt_options]

Parameter description:

From_addr: Mail Sender Address.

To_addrs: String list, Mailing address.

Msg: Send Message

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.


2. Mail in file form:

#!/usr/bin/env python3     #coding: utf-8       import smtplib    from email.mime.text import mimetext     from email.header import Header         sender =  ' * * * '     receiver =  '     subject '  =  ' python email test '     smtpserver =  ' smtp.163.com '      username =  ' * * * '     password =  ' * * * '          msg = mimetext (' Hello ', ' text ', ' utf-8 ')   #中文需参数 ' utf-8 ', single-byte characters not required     msg[' Subject '] = 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 ()

3, Html-style mail:

#!/usr/bin/env python3     #coding: utf-8       import smtplib    from email.mime.text import mimetext         sender =  ' * * * '     receiver =  ' * * * '     subject =  ' Python email test '     smtpserver  =  ' smtp.163.com '     username =  ' * * * *     password  =  ' * * * '         msg = mimetext (' 

4, HTML messages with pictures

#!/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 =  ' * * * '     receiver =  ' * * * '     subject =  ' python  email test '     smtpserver =  ' smtp.163.com '      username =  ' * * * '     password =  ' * * * '          msgroot = mimemultipart (' related ')     msgroot[' Subject ']  =  ' test message '         msgtext = mimetext (' <b >some <i>html</i> text</b> and an image.<br><br>good ! ', ' HTML ', ' utf-8 ')     msgroot.attach (msgtext)          fp = open (' h:\\python\\1.jpg ',  ' RB ')     msgImage =  Mimeimage (fp.read ())     fp.close ()          Msgimage.add_header (' content-id ',  ' <image1> ')     msgroot.attach (msgimage)          smtp = smtplib. SMTP ()     smtp.connect (' smtp.163.com ')     smtp.login (username,  Password)     smtp.sendmail (sender, receiver, msgroot.as_string ())      smtp.quit ()

5. Messages 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 =  ' * * * '     receiver =  ' * * * '     subject =  ' python  email test '     smtpserver =  ' smtp.163.com '      username =  ' * * * '     password =  ' * * * '          msgroot = mimemultipart (' related ')     msgroot[' Subject ']  =  ' test message '          #构造附件     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, receiver, msgroot.as_string ())      smtp.quit ()

6, Group Mail

#!/usr/bin/env python3     #coding: utf-8       import smtplib    from email.mime.text import mimetext         sender =  ' * * * *     receiver = [' * * * ‘,‘****‘,......]     subject =  ' Python email test '     smtpserver  =  ' smtp.163.com '     username =  ' * * * *     password  =  ' * * * '         msg = mimetext (' Hello ', ' text ', ' Utf-8 ' )         msg[' Subject '] = subject         smtp = smtplib. SMTP ()     smtp.connect (' smtp.163.com ')     smtp.login (username,  Password)     smtp.sendmail (sender, receiver, mSg.as_string ())     smtp.quit () 

7. Messages that are contained in various elements

#!/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 =  ' * * * '     receiver =  ' * * * '     subject =  ' python  email test '     smtpserver =  ' smtp.163.com '      username =  ' * * * '     password =  ' * * * '          # create message container - the correct mime type  is multipart/alternative.    msg = mimemultipart (' Alternative ')      msg[' Subject ']&Nbsp;=  "Link"         # create the body of  the message  (a plain-text and an html version) .     text =  "hi!\nhow are you?\nhere is the link you wanted:\ nhttp://www.python.org "    html = " "\  


This article is from the "baby god" blog, make sure to keep this source http://babyshen.blog.51cto.com/8405584/1887072

Python3 sending mail using smtplib and email modules

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.