Python3 example of how to use the SMTP protocol to send e-mail messages

Source: Internet
Author: User
Tags imap
The SMTP (Simple Mail Transfer Protocol) is simply the message Transfer Protocol, which is a set of rules for sending mail from the source address to the destination, and it controls the way the letters are relayed. The following article mainly introduces you to the Python3 how to use the SMTP protocol to send e-mail messages, the need for friends can refer to.





Objective



This article mainly introduces about the Python3 to send e-mail with SMTP protocol, before we describe how to use Python program to send mail to the designated mailbox, we need to introduce the relevant knowledge about e-mail.



Email history is longer than the web, and until now, email is a very wide range of services on the Internet.



Almost all programming languages support sending and receiving e-mails, but wait, before we start writing code, it's important to understand how e-mail works on the Internet.



Suppose our own e-mail address is me@163.com, the other's email address is friend@sina.com, now we use Outlook or foxmail such as software to write good mail, fill in the other's email address, click "Send", e-mail sent out. These e-mail software is known as Mua:mail user agent--mail users agent.



Email from MUA, not directly to the other computer, but sent to Mta:mail Transfer agent--Mail transmission agent, is those email service providers, such as NetEase, Sina and so on. Since our own e-mail is 163.com, so, email was first delivered to the MTA provided by NetEase, and then by NetEase's MTA sent to the other service providers, that is, Sina's MTA. This process may also pass through other MTA, but we don't care about the specific route, we only care about the speed.



After the email arrives at Sina's MTA, because the other party uses the @sina.com mailbox, therefore, Sina's MTA will send the email to the mail final destination mda:mail Delivery agent--the mail delivery agent. E-mail arrives MDA, quietly lying on a Sina server, stored in a file or a special database, we will this long-term preservation of the message of the place called an email. To get the mail, the other party must take the message to his computer via MUA from the MDA.



So, the journey of an email is:



MUA, MTA, MTA-----<-MUA <-recipient



With these basic concepts, writing a program to send and receive messages is essentially:



1. Write MUA to send the message to the MTA.



2. Write MUA to receive messages from the MDA.



When sending an email, the protocol used by MUA and MTA is Smtp:simple mail Transfer Protocol, and the subsequent MTA to another MTA is also using the SMTP protocol.



When receiving mail, MUA and MDA use two kinds of protocols: Pop:post Office Protocol, the current version is 3, commonly known as pop3;imap:internet message Access Protocol, the current version is 4, the advantage is not only to take mail, You can also directly manipulate messages stored on the MDA, such as moving from the inbox to the Trash, and so on.



When the mail client software sends an email, it will let you configure the SMTP server first, which is the MTA you want to send to. Assuming you're using 163 of your mailbox, you can't send it directly to Sina's MTA because it only serves Sina users, so, You have to fill in 163. SMTP server address: smtp.163.com, in order to prove that you are 163 users, the SMTP server also requires you to fill in the email address and mailbox password, so that MUA can normally send email through the SMTP protocol to the MTA.



Similarly, when receiving mail from MDA, the MDA server also asks you to verify your mailbox password to ensure that no one is impersonating you for your mail, so mail clients such as Outlook will ask you to fill out the POP3 or IMAP server address, email address, and password, MUA can successfully fetch messages from the MDA via a POP or IMAP protocol.



At the end of the Note: most e-mail service providers are required to manually open the SMTP send and pop delivery function, or only allow login on the Web page:



such as QQ mailbox






Next, let's start with our topic of how to send emails via python.



--------------------------------------------------------------------------------



Send a simple text message



SMTP is the protocol that sends messages, and Python's built-in support for SMTP can send plain text messages, HTML messages, and messages with attachments.



Python supports SMTP support with Smtplib and email two modules, email is responsible for structuring the mail, Smtplib is responsible for sending mail.



First, let's construct one of the simplest plain text messages:





from email.mime.text import MIMEText
msg = MIMEText('hello, this is axin...', 'plain', 'utf-8')


Note: when constructing a Mimetext object, the first parameter is the message body, the second parameter is the MIME subtype, the incoming ' plain ' represents plain text, and the final mime is ' text/ Plain ', finally, you must use UTF-8 encoding to ensure multi-language compatibility.



We are not allowed to have the content of the text, we also need to send the message to us to add header information. The header information contains information such as the sender and receiver, and the subject of the message.





msg = MIMEText ('hello, this is axin ...', 'plain', 'utf-8') #Message body
msg ['From'] = _format_addr ('Axin <% s>'% from_addr) #Email header, sender information
msg ['To'] = _format_addr ('aa <% s>'% to_addr) #Recipient information
msg ['Subject'] = Header ('test', 'utf-8'). encode () #message subject


After we have constructed the information we want to send, we only need to call Python's corresponding function and send it out via SMTP:





server = smtplib.SMTP (smtp_server, 25) #SMTP protocol default port is 25
server.set_debuglevel (1) #Print out all information about interaction with the SMTP server
server.login (from_addr, password) #Log in to the SMTP server
server.sendmail (from_addr, [to_addr], msg.as_string ()) #Send mail
server.quit ()


Weset_debuglevel(1)can print out all the information that interacts with the SMTP server. The SMTP protocol is a simple text command and response. The login () method is used to log on to the SMTP server bysendmail()sending an email, which can be sent to more than one person at a time, so a list is passed in, and the message body is a str, whichas_string()turns the Mimetext object into Str.



The complete code example is as follows:





from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr

import smtplib

def _format_addr (s): #format an email address
name, addr = parseaddr (s)
return formataddr ((Header (name, 'utf-8'). encode (), addr))

from_addr = 'fengxinlinux@sina.com' #Sender email address
password = '******' #Sender email password, don't tell you password =. =
to_addr = '903087053@qq.com' #Recipient email address
smtp_server = 'smtp.sina.com' #The MTA address of the email provider where the sender is located
#from_addr = input ('From:')
#password = input ('Password:')
#to_addr = input ('To:')
#smtp_server = input ('SMTP server:')

msg = MIMEText ('hello, this is axin ...', 'plain', 'utf-8') #Message body
msg ['From'] = _format_addr ('Axin <% s>'% from_addr) #Email header, sender information
msg ['To'] = _format_addr ('axin <% s>'% to_addr) #recipient information
msg ['Subject'] = Header ('test', 'utf-8'). encode () #message subject


server = smtplib.SMTP (smtp_server, 25) # The default port of the SMTP protocol is 25
server.set_debuglevel (1) #Print out all information about interaction with the SMTP server
server.login (from_addr, password) #Log in to the SMTP server
server.sendmail (from_addr, [to_addr], msg.as_string ()) #Send mail
server.quit ()
1


Run the program and we will find a new message in my test mailbox.






We will find that the other information is the same, but the recipient's information is not in our program to fill in the axin.



Because many mail service providers display the message, the recipient name is automatically replaced with the name of the user registration, but the display of the other recipient's name is not affected.



When I was testing, I sometimes sent emails that were judged by the email service providers as spam and were put in the trash ... As to what will be considered spam, I can not touch the clue.



Send a message with an attachment



Above we introduced how to send a text message, with the above knowledge, send a message with an attachment is actually very simple.



Messages with attachments can be viewed as messages that contain several parts: text and individual attachments, so you can construct a Mimemultipart object that represents the message itself, and then add a mimetext to it as the body of the message, Then continue to add the Mimebase object that represents the attachment:





# Mail object:
msg = MIMEMultipart ()
msg ['From'] = _format_addr ('Axin <% s>'% from_addr) #Email header, sender information
msg ['To'] = _format_addr ('axin <% s>'% to_addr) #recipient information
msg ['Subject'] = Header ('test', 'utf-8'). encode () #message subject

# The message body is MIMEText:
msg.attach (MIMEText ('hello, this is axin ...', 'plain', 'utf-8'))

# Adding an attachment is adding a MIMEBase to read an image from the local:
with open ('/ home / fengxin / picture / 11.jpg', 'rb') as fhandle:
mime = MIMEBase ('image', 'jpeg', filename = '11 .jpg ')
mime.add_header ('Content-Disposition', 'attachment', filename = '11 .jpg ')
mime.add_header ('Content-ID', '<0>')
mime.add_header ('X-Attachment-Id', '0')
# Read the contents of the attachment:
mime.set_payload (fhandle.read ())
# Encode with Base64:
encoders.encode_base64 (mime)
# Added to MIMEMultipart:
msg.attach (mime)


Then, by sending the MSG (note type to Mimemultipart) in the normal send process, you can receive the message with the attachment.



The complete code example is as follows:





from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase


import smtplib

def _format_addr (s): #format an email address
name, addr = parseaddr (s)
return formataddr ((Header (name, 'utf-8'). encode (), addr))

from_addr = 'Your email address' #Sender email address
password = 'your email password' #sender email password
to_addr = '903087053@qq.com' #Recipient email address
smtp_server = 'smtp.sina.com' #The MTA address of the email provider where the sender is located
#from_addr = input ('From:')
#password = input ('Password:')
#to_addr = input ('To:')
#smtp_server = input ('SMTP server:')


msg = MIMEMultipart ()
msg ['From'] = _format_addr ('Axin <% s>'% from_addr) #Email header, sender information
msg ['To'] = _format_addr ('axin <% s>'% to_addr) #recipient information
msg ['Subject'] = Header ('test', 'utf-8'). encode () #message subject

msg.attach (MIMEText ('hello, this is axin ...', 'plain', 'utf-8'))

with open ('/ home / fengxin / picture / 11.jpg', 'rb') as fhandle:
mime = MIMEBase ('image', 'jpeg', filename = '11 .jpg ')
mime.add_header ('Content-Disposition', 'attachment', filename = '11 .jpg ')
mime.add_header ('Content-ID', '<0>')
mime.add_header ('X-Attachment-Id', '0')
# Read the contents of the attachment:
mime.set_payload (fhandle.read ())
# Encode with Base64:
encoders.encode_base64 (mime)
# Added to MIMEMultipart:
msg.attach (mime)

server = smtplib.SMTP (smtp_server, 25) # The default port of the SMTP protocol is 25
server.set_debuglevel (1) #Print out all information about interaction with the SMTP server
server.login (from_addr, password) #Log in to the SMTP server
server.sendmail (from_addr, [to_addr], msg.as_string ()) #Send mail
server.quit ()
1 


After running. The test mailbox receives the message correctly,






Summarize


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.