📜 ⬆️ ⬇️

How to send an email using Python: a guide for dummies



In our blog, we write a lot about creating emails and working with e-mail. In the modern world, people receive a lot of letters, and some even have several mailboxes. All this complicates the process of their administration, which forces them to look for solutions to the problem. Not so long ago, we talked about how an engineer from the United States organized his letters using a neural network ( 1 , 2 ), and today we will talk about automating the sending of letters for different mailboxes.

The editor of the Motherboard edition, Michael Byrne (Michael Byrne) wrote a material on how to send emails for various mailboxes using Python. We present to your attention an adapted translation of this note.
')
Bern writes that he has as many as five email boxes: one personal, two university and two workers. There is also a sixth one, which he sometimes uses when he needs to quickly register somewhere. A large part of a journalist's life consists of quickly viewing and sorting emails, deleting them, adding them to favorites, and even reading these letters and responding to them. Bern says that he doesn’t even want to think about how much time it takes for all this every day.

The journalist admits that one day he thought, jokingly, that he needed to hire an assistant to manage his email. This, in turn, led to thinking about what instructions such an employee would need to give: "If the letter has this and that, do one, or if that's the case, do something else." This would be a specific set of rules applied to letters.

But when I see the phrase “rule set”, I immediately think about writing computer programs. Scrolling through my letters, I understand that it would be reasonable to embody my assistant in computer code.

However, in order to do this, it is necessary in some way to link e-mail boxes with a program for reading letters. This is done quite simply. In fact, emails are a set of text protocols for transferring information between networks; like the rest of the internet, in general. All these are just a few levels of protocols. The way we envision an email only displays its interface.

Even if you do not want to create a letter sorting program, managing emails as a set of data is quite interesting. Bern decided to use Python for solving the problem, since this language is really good for creating such things easily and intuitively, and is suitable even for non-programmers. Subsequent instructions are partially based on the email automation chapter from Al Sweigart’s Automate the Boring Stuff with Python book, which the journalist highly recommends as an introduction to programming and a reference guide for those who want to have fun with automation. This book is available for free under the Creative Commons license at automatetheboringstuff.com .

First you need to download Python (if it is not already installed). Also need any simple text editor. Sublime Text is perfect - you can download it here . ST is not free, but in test mode it can be used endlessly, although sometimes a purchase offer will appear. But he is worth his money.

Python can be used in two modes. The first is a command interpreter, where the user enters commands or snippets in Python into the console, and they are immediately executed (for example, print ("Hello, World!")). The second mode is Python scripts. In essence, this is just a set of Python commands in one or more files that can be invoked simultaneously from the console. In fact, these files are programs: sometimes small and simple (like what we look at next), they can grow to large projects.

If you just downloaded Python, you need to do two more things before you begin. First: Read the quick start writing guide for “Hello, World!” In Python. Second, take five minutes to read the guidelines for using modules in Python. Installing and importing Python extensions is a breeze.

So, let's begin.

0) Protocols for receiving mail: a brief guide


There are three main protocols for working with e-mail. The oldest of them is called Post Office Protocol (POP). Its essence is that the software for working with e-mail (not the browser) connects to a remote server, downloads letters to the user's computer, and they become available without an internet connection. It was a good idea at that time, when the Internet was connected infrequently, and it was normal not to have access to the Network, but at the present time this is almost not the case.

The current e-mail access standard is the Internet Message Access Protocol (IMAP). It is much faster and more relevant to how the Internet is used today. It allows multiple users to connect to the same mailbox and maintains their connection throughout the session.
Web browsers gain access to e-mail using an additional protocol, HTTP, but it is based on the same POP and IMAP.

Basically, POP (current POP3 version) and IMAP are used to receive messages from the server. But in order to send a letter, you need another protocol - SMTP (Simple Mail Transfer Protocol). This is because you can not just send a letter to the recipient. It must be sent to the server from which the recipient downloads this email using IMAP and POP3.

1) Connecting the python SMTP module


First we need a suitable Python module. Smtplib comes with Python, so no additional steps need to be taken, just enter this line in the console:

import smtplib 

To get help on a module (and to make sure that it is connected), you can use the help function:

 help(smtplib) 

It should be noted that this function works with any module.

2) Connect to email server


First of all, you need to create an smtplib object, which can be viewed as a portal that gives access to the connection and various tools for working with it from the smtplib module.

In this case, the function that returns the required object takes two parameters or arguments. The first argument contains the domain name, that is, the email address that starts with “smtp”, as shown below. The second argument is the port number to which the connection will be made on the email server. It almost always takes the value 587 in accordance with the TLS encryption standard. Very rarely there are services using port 465.

So, you need to write the following:

 smtpObj = smtplib.SMTP('smtp.gmail.com', 587) 

It turns out that the variable smtpObj is an object of type SMTP. You can verify this if you enter the variable name in the console and confirm the input. The address of her memory cell and type will appear on the screen (provided that you entered the previous command correctly). The variable smtpObj can be called as you like, as long as it is a valid variable name in Python.

3) Encryption


The next thing you need to do to establish a connection is to “tell” the SMTP object that the message should be encrypted. To do this, enter this line in the console and press Enter:

 smtpObj.starttls() 

This is what we did: we told Gmail that we wanted our connection to be encrypted using the Transport Layer Security (TLS) protocol, which today is the standard for Internet communications. TLS itself is not a cryptographic algorithm; rather, it states that it is necessary to use encryption or the connection should not be established.

In response, you should receive a confirmation:

 2.0.0 Ready to start TLS 

The important point is that if you skip this step and go straight to authorization, error messages will appear on the screen. This is because Gmail uses encryption using the HTTPS protocol, that is, all the same HTTP, " wrapped " in an additional TLS-protocol.

5) Authorization


In order to log in, you just need to write

 smtpObj.login('justkiddingboat@gmail.com','just123kidding') 

At this stage, the password from the email, so to speak, flies into the unknown, which is quite dangerous. This is not a problem on the local computer, but if you really automate the work with e-mail using a Python script, you need to be careful and think twice before publishing the script code anywhere or uploading the file to third-party sites.

5) Sending a message


The advantage of using environments with a command interpreter is that even in the absence of any information — for example, descriptions of sending a letter — you can ask the interpreter about it. To do this, simply enter the following command:

 help(smtpObj) 

Slightly scrolling the page you can see the desired method:



The interpreter will even display an example of its use:



Note that in the example above there is no authorization command. This is due to the fact that the program was connected to the user's computer, and not to the remote email server. For our case, we write the following:

 smtpObj.sendmail("justkiddingboat@gmail.com","michael.byrne@vice.com","go to bed!") 


It worked!



6) End the connection


To end the connection, just use the following command:

 smtpObj.quit() 

Naturally, sending messages is just a small part of what you can do with email using Python. Bern advises you to continue learning with Swigarte’s book to learn how to work with e-mail using IMAP.

I warn you: the code will still be a bit. By morning, you can do whatever you want with your scripts in Python with your mail.

And, of course, you need to understand that such automation should be used only to facilitate the work with e-mail, and not to fill up people with unnecessary spam.

Source: https://habr.com/ru/post/281915/


All Articles