Email message format

In this section, we're going to learn about the email message format. Email messages consist of three primary components:

  • The receiver's email address
  • The sender's email address
  • The message

There are other components also included in the message format, such as the subject line, email signatures, and attachments.

Now, we're going to see a simple example of sending a plain text email from your Gmail address, in which you'll learn about writing an email message and sending it. Now, create a script, write_email_message.py, and write the following content in it:

import smtplib
import getpass

host_name = "smtp.gmail.com"
port = 465

sender = 'sender_emil_id'
receiver = 'receiver_email_id'
password = getpass.getpass()

msg = """
Subject: Test Mail
Hello from Sender !!"""

s = smtplib.SMTP_SSL(host_name, port)
s.login(sender, password)
s.sendmail(sender, receiver, msg)
s.quit()

print("Mail sent successfully")

Run the script and you'll get the following output:

student@ubuntu:~/work/Chapter_11$ python3 write_email_message.py
Output:
Password:
Mail sent successfully

In the preceding example, we used the smtplib Python module to send an email. Make sure you're sending an email from a Gmail ID to the receiver. The sender variable saves the sender's email address. In the password variable, you can either enter your password or you can prompt for a password using the getpass module. Here, we prompt for the password. Next, we created a variable named msg, which will be our actual email message. In that, we first mentioned a subject and then the message we want to send. Then, in login(), we mentioned the sender and password variables. Next, in sendmail(), we mentioned the sender, receivers, and text variables. So, using this process, we sent the email successfully.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset