Emails are a typical method of official communication nowadays, and they are also useful for transferring files from one person to another. Almost everyone who has an online identity or merely utilizes it has their email address, whether it’s Gmail or Outlook.
One of the many cool things you can do with Python is to send and receive emails. Python programming libraries may be used to send emails or to display a list of all the emails in your inbox. Python may also be used to handle certain simple tasks, such as marking emails as read.
And I’m going to show you how to do it yourself in this blog.
Before we get started with the code, you need to have a fundamental understanding of email and mail servers.
Mail servers are servers that manage emails. For example, Outlook, Gmail, Yahoo, and Hotmail all have their mail servers that handle respective email services. Mail servers may be further divided into two types:
Simple Mail Transfer Protocol (SMTP) is an acronym for Simple Mail Transfer Protocol.
This server is in charge of transmitting or transferring mail from one server to another; for example, when you send an email to someone, you usually utilize the SMTP server.
Internet Message Access Protocol (IMAP) is an acronym for Internet Message Access Protocol.
This server is in charge of storing and listing messages from your server; for example, the IMAP server is often used when you access Gmail or Outlook.
SSL (Secure Socket Layer) and TLS (Transport Layer Security) are the two encryption methods used for emails (Transport Layer Security).
You will use one of these protocols to connect to any mail server.
The server is allocated a port for each protocol.
SSL — port 465 TLS — port 587
Although both protocols are supported by Gmail and Outlook, we will only utilize TLS in this tutorial for simplicity.
Now that we’ve covered mail servers, let’s write our first python script to deliver mail.
To send Gmail or Outlook mail, we’ll use Python’s smtplib package. You don’t need to download this library because it’s already built into Python.
Here’s how the script would look like:
Vs Code Screenshot
The script may appear confusing, but we’ll go over each function and class of the script line by line so you can understand how to utilize it.
piece of code
Importing the smtplib and getpass libraries is the first step in the script. We’re going to utilize the getpass library to get the password from the user.
Following that, we ask the user to provide their mail account details, which will be used to send the email. To ask the user for their password, we use getpass(). Because we’re using getpass(), the user’s password won’t be shown on the screen; instead, it’ll be kept in the variable.
The next step is to configure the SMTP server host and port. The host will be set to Gmail SMTP server if the supplied email ID is a Gmail account, or Outlook SMTP server if it is an Outlook account.
As we stated in the ‘SSL and TLS’ section, we changed the port to 587. The script will deliver an error message and terminate if the entered email ID cannot be recognized as Gmail or Outlook.
The SMTP class object, which will be used to conduct the tasks, will be created next. We make an object of the smtplib.SMTP class and store it with the nameserver.’ The hostname and port are required arguments for the class object.
We call the ehlo() method of the class object once we’ve constructed the object, which is used to send a welcome message to the mail server. This step is critical, since failing to do so may result in communication issues with the mail server.
We invoke the starttls() method to start TLS encryption after obtaining a successful response from the server. This step is only necessary for TLS connections; SSL connections do not require it.
The login() method is then used to log into the mail account. The email ID and password, which we had acquired from the user, are required arguments for the function.
We ask the user for the recipient’s email address, the email’s topic, and the email’s content after they have successfully logged in.
Finally, we execute the sendmail() method with three parameters: the sender mail ID, the recipient mail ID, and the message contents (created by merging mail subject and mail content).
Here is the full code:
import smtplib import getpass # Get email ID and password from user email = input("Enter email ID: ") password = getpass.getpass("Enter password: ") # Set SMTP host and port if "gmail" in email: host = "smtp.gmail.com" port = 587 elif "outlook" in email: host = "smtp-mail.outlook.com" port = 587 else: print("Invalid email ID, please try again") exit(0) # Create SMTPLib object and contact server server = smtplib.SMTP(host, port) check = server.ehlo() if check == 250: print("Successfully contacted mail server") else: print("Unable to contact server") exit(0) # Start TLS encryption (only to be done if conencting to port 587 i.e. TLS) server.starttls() # Logging into the server try: server.login(email, password) print("Login successful") except smtplib.SMTPAuthenticationError as ex: print("Exception:", ex) exit(0) # Get email details from user sender_mail = email receiver_email = input("Enter receiver's email: ") subject = input("Enter email subject: ") content = input("Enter email content: ") # Create email body by merging emails object and content body = "Subject: " + subject + '\n' + content # Send the mail output = server.sendmail(sender_mail, receiver_email, body) if not len(output): print("Send mail successfully") else: print("Unable to send mail, please try again") exit(0)
And that’s it, you have successfully sent a mail through Python.
I’ve just discussed sending mail with Python in this blog. I’ll be starting another blog shortly on getting emails from accounts using python to contact IMAP servers.
Thank you for your interest in reading this article. This knowledge should help you in sending emails using python, in my opinion.
Don’t forget to follow me on Medium if you want to see more pieces like this.
More content at plainenglish.io