The email has a long history than the Web. Until now, it is also a very widely used service on the Internet. Almost all programming languages support sending and receiving e-mail, but wait a minute before we start coding, it’s necessary to figure out how e-mail works on the Internet.
1. How Email Works On The Internet.
1.1 MUA ( Mail User Agent ).
- Assuming our own e-mail address is [email protected] and the other party’s e-mail address is [email protected].
- Now we use software like Outlook to write the e-mail, fill in the other party’s e-mail address, click “Send”, and the e-mail will be sent out.
- These E-mail software are called MUA: Mail User Agent.
1.2 MTA ( Mail Transfer Agent ).
- Email is sent from MUA, not directly to the other party’s computer, but to MTA: Mail Transfer Agent, which is the email service providers, such as Google, Yahoo, and so on.
- Since our own e-mail is google.com, e-mail is first delivered to the MTA provided by Google, and then from google’s MTA to the other service provider such as yahoo’s MTA.
- There may be other MTAs in the process, but we don’t care about the specific route.
1.3 MDA ( Mail Delivery Agent ).
- After the email arrives at Yahoo’s MTA, because the other party uses the mailbox of @yahoo.com, Yahoo’s MTA will send the email to the final destination of the mail which is MDA: Mail Delivery Agent.
- When Email arrives at MDA, it lies quietly on one of Yahoo’s servers and stores it in a file or special database. We call this place where email is stored for a long time as an e-mail box.
- Similar to ordinary mail, an email will not directly reach the other party’s computer, because the other party’s computer may not turn on, or may not connect to the internet. In order for the other party to access the mail, it must transfer the mail from MDA to its own computer through MUA.
2. How To Write Code To Send/Receive Email.
- With these basic concepts, writing programs to send and receive e-mails just need to follow two steps.
- Write MUA to send mail to MTA.
- Write MUA to receive mail from MDA.
- When sending mail, the protocol used by MUA and MTA is SMTP: Simple Mail Transfer Protocol, and later MTA to another MTA is also SMTP protocol.
- When receiving mail, MUA and MDA use two protocols: 1) POP: Post Office Protocol, the current version is 3, commonly known as POP3; 2) IMAP: Internet Message Access Protocol, the current version is 4, the advantage of the IMAP protocol is that not only can get mail, but also can directly operate the mail stored on MDA, such as moving from the inbox to the garbage bin, and so on.
- When email client software sends mail, it will let you configure the SMTP server first, which MTA you want to send to.
- In order to prove that you are a user of this mail server, the SMTP server also requires you to fill in the mailbox address and password, so that MUA can send emails to MTA through SMTP protocol normally.
- When receiving mail from MDA, the MDA server also requires validation of your mailbox password to ensure that no one pretends to collect your mail.
- Therefore, mail clients such as Outlook will require you to fill in POP3 or IMAP server address, mailbox address and password, so that MUA can smoothly retrieve mail from MDA through POP or IMAP protocol.
3. Send Email Through SMTP In Python.
3.1 Send SMTP Email In Python.
- SMTP is a protocol for sending emails. Python has built-in support for SMTP. It can send plain text mail, HTML mail, and mail with attachments.
- Python supports SMTP with two modules:
smtplibmodule is responsible for sending mail.
- Below is python code that can construct the simplest plain text message.
from email.mime.text import MIMEText msg = MIMEText('hello world from Python...', 'plain', 'utf-8')
- Notice that when constructing MIMEText objects, the first parameter is the mail body, the second parameter is the subtype of MIME, and the input ‘plain’ represents the plain text. The last MIME type is ‘text/plain’. Finally, utf-8 coding charset must be used to ensure multilingual compatibility.
- Then you can send the above email message using SMTP protocol like below.
# input sender email address and password: from_addr = input('From: ') password = input('Password: ') # input receiver email address. to_addr = input('To: ') # input smtp server ip address: smtp_server = input('SMTP server: ') # import smtplib module import smtplib # create smtp server object, the default smtp protocol port number is 25. server = smtplib.SMTP(smtp_server, 25) # set debug level to 1 to print out all interact data between this program and SMTP servers server.set_debuglevel(1) # login smtp server with the provided sender email and password. server.login(from_addr, password) # send email to smtp server and quit. The to_addr is a list of email address then can send one email to multiple receiver. server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit()
3.2 Send SMTP Email With Complete Information In Python.
- If you look at the above email that you receive in your mailbox, you will find that the email does not have the topic, the recipient field’s name is not displayed as a friendly name such as Trump<[email protected]>, and obviously received mail was not displayed in the recipient list.
- All these are because the mail’s topics, how to display the sender, recipient and other information are not sent to MTA through SMTP protocol, but contained in the text sent to MTA.
- Therefore, we must add the From, To, and Subject to MIMEText to send a complete email.
from email import encoders from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr, formataddr # import python smtplib module import smtplib # this function will parse the email address first to get the email user's real name and address. # then it will encode the user name using utf-8 to avoid encoding error. # then it will call formataddr function to construct the email address again. def _re_format_addr(s): # parse email to get user real name and email address. name, addr = parseaddr(s) name_encoded = (Header(name, 'utf-8').encode() return formataddr(name_encoded, addr)) # get sender email, password, receiver email and smtp server ip address. from_addr = input('From: ') password = input('Password: ') to_addr = input('To: ') smtp_server = input('SMTP server: ') # create MIMEText object msg = MIMEText('hello world email from Python', 'plain', 'utf-8') # add from, to and subject to the MIMEText object. msg['From'] = _re_format_addr('Trump <%s>' % from_addr) msg['To'] = _re_format_addr('Admin <%s>' % to_addr) msg['Subject'] = Header('This email sent from Python code', 'utf-8').encode() server = smtplib.SMTP(smtp_server, 25) server.set_debuglevel(1) server.login(from_addr, password) server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit()
- Above is just a simple example of how to send pure text email through SMTP in python. We will introduce more detailed email sending options such as sending Html format email, image email, and attachment email in later articles.