Python – Email Messages
Email is a service which allows us to send the message in electronic mode over the internet. It offers an efficient, inexpensive and real time mean of distributing information among people.
Each user of email is assigned a unique name for his email account. This name is known as E-mail address. Different users can send and receive messages according to the e-mail address.
The username and the domain name are separated by @ (at) symbol.
E-mail addresses are not case sensitive.
Spaces are not allowed in e-mail address.
The first five lines of an E-mail message is called E-mail header. The header part comprises of following fields:
The From field indicates the sender’s address i.e. who sent the e-mail.
The Date field indicates the date when the e-mail was sent.
The To field indicates the recipient’s address i.e. to whom the e-mail is sent.
The Subject field indicates the purpose of e-mail. It should be precise and to the point.
CC stands for Carbon copy. It includes those recipient addresses whom we want to keep informed but not exactly the intended recipient.
BCC stands for Black Carbon Copy. It is used when we do not want one or more of the recipients to know that someone else was copied on the message.
Greeting is the opening of the actual message. Eg. Hi Sir or Hi Guys etc.
It represents the actual content of the message.
This is the final part of an e-mail message. It includes Name of Sender, Address, and Contact Number.
Python has EmailMessage class which can be used build email messages.
This class ahs the required methods to customize different parts of the email message like – the TO and FROM tags, the Subject Line as well as the content of the email.
In the below example we create an email message with all the necessary parts of an email. Once we print out the content of the message we can see the complete email.
import email.message, email.policy, email.utils, sys text = """Welcome to TutorialsPoint - Simple Easy Learning""" message = email.message.EmailMessage(email.policy.SMTP) message['To'] = '[email protected]' message['From'] = 'Learn
' message['Subject'] = 'A mail To you' message['Date'] = email.utils.formatdate(localtime=True) message['Message-ID'] = email.utils.make_msgid() message.set_content(text) sys.stdout.buffer.write(message.as_bytes())
When we run the above program, we get the following output −
> To: [email protected] From: Learn
Subject: A mail To you Date: Wed, 13 Jun 2018 06:51:09 -0700 Message-ID: <[email protected]> Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit MIME-Version: 1.0 Welcome to TutorialsPoint - Simple Easy Learning