Как отправить сообщение на почту python

от admin

email : Examples¶

Here are a few examples of how to use the email package to read, write, and send simple email messages, as well as more complex MIME messages.

First, let’s see how to create and send a simple text message (both the text content and the addresses may contain unicode characters):

Parsing RFC 822 headers can easily be done by the using the classes from the parser module:

Here’s an example of how to send a MIME message containing a bunch of family pictures that may be residing in a directory:

Here’s an example of how to send the entire contents of a directory as an email message: 1

Here’s an example of how to unpack a MIME message like the one above, into a directory of files:

Here’s an example of how to create an HTML message with an alternative plain text version. To make things a bit more interesting, we include a related image in the html part, and we save a copy of what we are going to send to disk, as well as sending it.

If we were sent the message from the last example, here is one way we could process it:

Up to the prompt, the output from the above is:

Thanks to Matthew Dixon Cowles for the original inspiration and examples.

Previous topic
Next topic

This Page

Navigation

  • index
  • modules |
  • next |
  • previous | »

© Copyright 2001-2023, Python Software Foundation.
This page is licensed under the Python Software Foundation License Version 2.
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
See History and License for more information.

The Python Software Foundation is a non-profit corporation. Please donate.

Last updated on Mar 13, 2023. Found a bug?
Created using Sphinx 4.5.0.

Как отправить электронное письмо с помощью Python: руководство для «чайников»

В нашем блоге мы много пишем о создании email-рассылок и работе с электронной почтой. В современном мире люди получают множество писем, а у некоторых даже есть несколько почтовых ящиков. Все это усложняет процесс их администрирования, что вынуждает искать пути решения проблемы. Не так давно мы рассказывали о том, как инженер из США упорядочивал свои письма с помощью нейронной сети (1, 2), а сегодня речь пойдет об автоматизации отправки писем для разных почтовых ящиков.

Редактор издания Motherboard Майкл Берн (Michael Byrne) написал материал о том, как отправлять электронные письма для различных почтовых ящиков с помощью Python. Мы представляем вашему вниманию адаптированный перевод этой заметки.

Берн пишет, что у него есть целых пять электронных ящиков: один личный, два университетских и два рабочих. Есть ещё и шестой, который он иногда использует, когда нужно быстро где-то зарегистрироваться. Немалая часть жизни журналиста состоит из быстрого просмотра и сортировки электронных писем, их удаления, добавления в избранное, и даже чтения этих писем и ответа на них. Берн говорит, что даже не хочет задумываться о том, сколько на все это уходит времени каждый день.

Журналист признается, что однажды в шутку подумал, что ему надо нанять помощника для управления своей электронной почтой. Это, в свою очередь, привело к размышлениям о том, какие указания такому сотруднику надо было бы давать: «Если в письме есть то-то и то-то, сделай одно, или если вот это так, сделай кое-что другое». Это был бы определённый набор правил, применённый к письмам.

Тем не менее, чтобы сделать это, необходимо каким-то образом связать электронные ящики с программой для чтения писем. Это делается довольно просто. На самом деле, электронные письма – это набор текстовых протоколов для передачи информации между сетями; как и весь остальной интернет, в общем. Всё это лишь несколько уровней протоколов. То, как мы представляем себе электронную почту, отображает лишь ее интерфейс.

Даже если вы не хотите создавать сортирующую письма программу, управлять электронными письмами как набором данных довольно интересно. Берн решил использовать для решения задачи Python, так как этот язык действительно хорош для лёгкого и интуитивного создания подобных вещей, и подходит даже для не-программистов. Последующие инструкции частично основаны на главе про автоматизацию электронной почты из книги Эла Свейгарта (Al Sweigart) «Automate the Boring Stuff with Python», которую журналист очень рекомендую и как введение в программирование, и как справочное руководство для тех, кто хочет повеселиться с автоматизацией. Эта книга доступна бесплатно под лицензией Creative Commons на automatetheboringstuff.com.

Для начала потребуется скачать Python (если он еще не установлен). Также потребуется любой простой текстовый редактор. Отлично подойдет Sublime Text — его можно скачать здесь. ST не бесплатный, но в тестовом режиме им можно пользоваться бесконечно, хоть иногда и будет появляться предложение о покупке. Но своих денег он стоит.

Python можно использовать в двух режимах. Первый – это командный интерпретатор, где пользователь вводит команды или сниппеты на Python в консоль, и они сразу же выполняются (например, print(«Hello, World!»)). Второй режим – это скрипты на Python. По сути, это просто набор команд на Python в одном или нескольких файлах, которые могут быть вызваны одновременно из консоли. Фактически, эти файлы – это программы: иногда маленькие и простые (как то, что мы рассмотрим дальше), они могут разрастаться до больших проектов.

0) Протоколы для получения почты: краткое руководство

Существуют три основных протокола для работы с электронной почтой. Самый старый из них называется POP (Post Office Protocol). Его суть в том, что программное обеспечение для работы с электронной почтой (не браузер) подключается к удалённому серверу, скачивает письма на компьютер пользователя, и они становятся доступны без подключения к интернету. Это было хорошей идеей в те времена, когда к интернету подключались нечасто, и было нормальным не иметь выхода в Сеть, но в настоящее время такого почти не бывает.

Текущим стандартом доступа к электронным ящикам является протокол IMAP (Internet Message Access Protocol). Он намного быстрее и больше соответствует тому, как интернет используется в наши дни. Он позволяет нескольким пользователям подключаться к одному ящику и поддерживает их соединение в течение всей сессии.
Веб-браузеры получают доступ к электронной почте с помощью дополнительного протокола – HTTP, но в основе лежат всё те же POP и IMAP.

В основном для получения писем с сервера используются POP (актуальная версия POP3) и IMAP. Но для того чтобы отправить письмо, нужен другой протокол – SMTP (Simple Mail Transfer Protocol). Всё потому, что нельзя просто отправить письмо получателю. Его нужно отправить на сервер, с которого получатель это письмо скачает, используя IMAP и POP3.

1) Подключение SMTP-модуля Python

Для начала нам нужен подходящий модуль Python. Smtplib поставляется вместе с Python, поэтому не нужно предпринимать дополнительных действий, достаточно просто ввести эту строку в консоль:

Для получения справки по модулю (и чтобы удостовериться, что он подключился), можно использовать функцию help:

Следует отметить, что эта функция работает с любым модулем.

2) Подключение к серверу электронной почты

Прежде всего, нужно создать объект smtplib, который можно рассматривать как некий портал, дающий доступ к подключению и различным инструментам работы с ним из модуля smtplib.

В данном случае функция, возвращающая необходимый объект, принимает два параметра или аргумента. Первый аргумент содержит доменное имя, то есть адрес электронной почты, начинающийся с «smtp», как показано ниже. Второй аргумент – это номер порта, к которому будет осуществляться подключение на сервере электронной почты. Он почти всегда принимает значение 587 в соответствии со стандартом шифрования TLS. Очень редко встречаются сервисы, использующие порт 465.

Итак, нужно написать следующее:

Получается, что переменная smtpObj является объектом типа SMTP. В этом можно убедиться, если ввести имя переменной в консоль и подтвердить ввод. На экране появятся адрес её ячейки памяти и тип (при условии, что вы ввели предыдущую команду правильно). Переменную smtpObj можно назвать, как угодно, лишь бы это было допустимое в Python имя переменной.

3) Шифрование

Следующее, что нужно сделать для установления соединения, это «сказать» SMTP-объекту, что сообщение должно быть зашифровано. Для этого следует ввести в консоль эту строку и нажать Enter:

Вот что мы сделали: мы сообщили Gmail, что хотим, чтобы наше соединение шифровалось с помощью протокола TLS (Transport Layer Security), который на сегодняшний день является стандартом для интернет-коммуникаций. Сам по себе TLS не является криптографическим алгоритмом, он скорее сообщает, что необходимо использовать шифрование или соединение не должно быть установлено.

В ответ вы должны получить подтверждение:

Важный момент — если пропустить этот шаг и сразу перейти к авторизации, то на экране появятся сообщения об ошибках. Всё потому, что Gmail применяет шифрование с использованием протокола HTTPS, то есть всё тот же НТТР, «обёрнутый» в дополнительный TLS-протокол.

5) Авторизация

Для того чтобы авторизоваться, нужно всего лишь написать

На данном этапе пароль от электронной почты, так сказать, улетает в неизвестность, что довольно опасно. Это не проблема на локальном компьютере, но если вы действительно автоматизируете работу с электронной почтой с помощью скрипта на Python, то нужно проявить осторожность и дважды подумать, прежде чем публиковать код скрипта где-либо или загружать файл с ним на сторонние площадки.

5) Отправка сообщения

Плюс использования сред с командным интерпретатором заключается в том, что даже при отсутствии какой-либо информации — например, описания отправки письма — можно спросить об этом сам интерпретатор. Для этого нужно просто ввести следующую команду:

Немного поскроллив страницу можно увидеть нужный метод:

Интерпретатор даже выведет пример его использования:

Заметьте, что в примере выше отсутствует команда авторизации. Это связано с тем, что программа подключалась к компьютеру пользователя, а не к удалённому серверу электронной почты. Для нашего случая напишем следующее:

6) Завершение соединения

Для завершения соединения достаточно использовать такую команду:

Естественно, отправка сообщений – это всего лишь малая часть того, что можно делать с электронной почтой с помощью Python. Берн советует продолжить обучение с книгой Свейгарта, чтобы узнать, как работать с электронной почтой, используя IMAP.

How to Send an Email in Python

How to Send an Email in Python

What do you need in order to send an email with Python? Some basic programming and web knowledge along with elementary Python skills. We assume you’ve already had a web app built with this language and now you need to extend its functionality with notifications or other email sending options.

With numerous code examples, in this 2022 tutorial, we’ll guide you through the fundamental steps of sending different types of emails via an SMTP (Simple Mail Transfer Protocol) server using Python.

Note: Written and tested on Python 3.6.9. See more Python-related repositories on Github.

What email sending options with Python are there?

The two primary ways of sending emails in Python are using an SMTP method and the second one is a transactional email service. Let’s take a closer look at the two and unpack how they work.

Send emails with Python and SMTP

The first good news about Python is that in its standard library there is a built-in smtplib module that is used for sending emails via SMTP connection. The module uses the standard RFC 821 protocol, so no extra installations or tricks are required.

Send emails with Python using Transactional Email Services

If you decide to set up the sending functionality in your Python app without built-in SMTP, you can integrate third-party transactional email API.

One of the main reasons to go this route is if a strong deliverability rate is a critical factor for you. Most third-party API services have analytical tools and provide scalability opportunities you might need as your project grows.

Sending emails in Python: A Step-by-Step Guide

How to send emails using SMTP

The built-in smtplib module can be imported using the following statement:

To send an email later, create one SMTP object:

smtpObj = smtplib.SMTP( [host [, port]] )

  • host − this is an optional argument and is the host running your SMTP server. The IP address of the host or a domain name can be specified.
  • port − if the host argument is specified, specify a port, where the SMTP server is listening.
  • local_hostname − if the used SMTP server is running on your local machine, specify localhost.

An SMTP object has an instance method called sendmail that is used to send a message and has three parameters:

  • sender − string with the address of the sender.
  • receivers − list of strings, one for each recipient.
  • message − a message as a string formatted as specified in RFCs.

smtpObj.sendmail(sender, receivers, message)

To make sure that the email module has been imported properly and get the full description of its classes and arguments, type in an interactive Python session:

Refer to Python documentation to further review the rest of the SMTP Objects (e.g., smtp.ehlo ; smtp.send_message(msg) etc.) and how to apply them.

Below you can find an example of a simple Python script that shows how one can send an email from a local SMTP.

However, this code wouldn’t work.

Firstly, you’ll need an actual working SMTP server. Secondly, most recipients reject emails from untrusted sources. On top of that, getting all the relevant validations and certifications for other servers to approve your emails is not easy.

Using a third-party API for sending functionality in your Python app is the best way to go about it. One like Mailtrap Email Sending, where the tedious work of ensuring your emails get delivered is already done, and there is no need to set up your own SMTP server.

How to send HTML emails in Python?

In most cases, you need to add some formatting, links, or images to your email notifications. We can simply put all of these with the HTML content. For this purpose, Python has an email package.

We will deal with the MIME message type, which can combine HTML/CSS and plain text. In Python, it is handled by the email.mime module.

It is better to write a text version and an HTML version separately and then merge them with the MIMEMultipart("alternative") instance. It means that such a message has two rendering options accordingly. In case an HTML isn’t rendered successfully for some reason, a text version will still be available.

Input:

Output:

How to send emails with attachments?

The next step in mastering sending emails with Python is attaching files. Attachments are still the MIME objects, but we need to encode them with the base64 module that encodes all binary data into ASCII characters.

A couple of important points about the attachments:

    Python lets you attach standard .txt, rich text format, and all other main text files, images, audio files, and even applications. You just need to use the appropriate email class like:

In transactional emails, PDF files are the most frequently used: we usually get receipts, tickets, boarding passes, order confirmations, and many other authentication-related documents. So let’s review how to send a boarding pass as a PDF file.

Input:

Output:

To attach several files, you can call the message.attach() method several times.

How to send emails to multiple recipients using Python?

Sending multiple emails to different recipients and making them personal is the special thing about emails in Python.

To add several more recipients, you can just type their addresses separated by a comma and add CC and BCC. But if you work with bulk email sending, Python will save you with loops.

One of the options is to create a database in a .csv format (we assume it is saved to the same folder as your Python script).

We often see our names in transactional or even promotional examples. Here is how we can make it with Python.

Let’s organize the list in a simple table with just two columns: name and email address. It should look like the following example:

The code below will open the file and loop over its rows line by line, replacing the with the value from the “name” column.

Input:

After running the script, we get the following response:

Output:

In our Mailtrap inbox, we see two messages: one for John Johnson and another for Peter Peterson, delivered simultaneously:

How to send emails with images?

Images, even if they are a part of the email message body, are still attachments as well. There are three types of them:

  • CID attachments (embedded as a MIME object)
  • Base64 images (inline embedding)
  • Linked images

We have described their peculiarities, pros and cons, and compatibility with most email clients in this post.

To add a CID attachment, we will create a MIME multipart message with MIMEImage component:

Output:

The CID image is shown as part of the HTML message and as an attachment. Messages with this image type are often considered spam: check the Analytics tab in Mailtrap to see the spam rate and recommendations for improvement. In most cases, many email clients – Gmail in particular – don’t display CID images. So let’s review how to embed a base64 encoded image.

Here we will use base64 module and experiment with the same image file:

Output:

Now the image is embedded into the HTML message and is not available as an attached file. Python has encoded our jpg image, and if we go to the HTML Source tab, we will see the long image data string in the img src.

Sending emails with Python via Gmail

You can configure your production server when ready to send your custom emails to a real recipient’s email address. It also depends on your needs, goals, and preferences: your local host or any external SMTP.

One of the most popular options is Gmail so let’s take a closer look at it.

We often see titles like “How to set up a Gmail account for development”. It means you will create a new Google account and use it for a particular purpose.

To be able to send emails via your Gmail account, you need to provide access to it for your application. You can Allow less secure apps or take advantage of the OAuth2 authorization protocol. It’s way more difficult but recommended due to security reasons.

Further, to use Gmail’s SMTP server, you need to know:

  • the server name = smtp.gmail.com
  • port = 465 for SSL/TLS connection (preferred)
  • or port = 587 for STARTTLS connection
  • username = your Gmail email address
  • password = your password

If you tend to simplicity, then you can use Yagmail, the dedicated Gmail/SMTP. It makes email sending really easy. Just compare the above examples with these several lines of code:

Test emails with Mailtrap Email Testing

When creating a new app or adding any functionality, especially when doing it for the first time, it’s essential to experiment on a test server. Here is a brief list of reasons:

  1. You won’t hit your friends’ and customers’ inboxes. This is vital when you test bulk email sending or work with an email database.
  2. You won’t flood your inbox with testing emails.
  3. Your domain won’t be blacklisted for spam.

A testing SMTP server environment imitates the work of a real 3rd party web server. In the following examples, we’ll use Mailtrap Email Testing, which allows devs to capture SMTP traffic from staging and inspect and debug emails before they go out to actual recipients.

On top of that, the Email Testing can help validate your HTML/CSS, analyze the email’s content, and give a relevant spam score. The tool is easy to set up; all you need is to copy the credentials generated by the app and paste them into your code.

Here is how it looks in practice:

Mailtrap makes things even easier. Go to the Integrations section in the SMTP settings tab and get the ready-to-use template of the simple text message with your Mailtrap credentials. The most basic option for instructing your Python code on who sends what to who is the sendmail() instance method:

The code snippet looks pretty straightforward, right? Let’s take a closer look at it and add some error handling (see the #explanations in between). To catch errors, we use the “try” and “except” blocks. Refer to the documentation for the list of exceptions here.

Once you get the Sent result in Shell, you should see your message in your Mailtrap inbox:

If you prefer working in the local environment, the local SMTP debugging server might be an option. For this purpose, Python offers an smtpd module. It has a DebuggingServer feature, which will discard messages you are sending out and will print them to stdout. It is compatible with all operations systems.

Set your SMTP server to localhost:1025

python -m smtpd -n -c DebuggingServer localhost:1025

In order to run SMTP email server on port number 25, you’ll need root permissions:

sudo python -m smtpd -n -c DebuggingServer localhost:25

It will help you verify whether your code is working and point out the possible problems if there are any. However, it won’t allow you to check how your HTML email template is rendered.

Next steps with emails in Python

We have demonstrated just basic options of sending emails with Python to describe the logic and a range of its capabilities. We recommend reviewing the Python documentation and experimenting with your own code to get great results!

There are a bunch of various Python frameworks and libraries which make creating apps more elegant and dedicated. In particular, some of them can help improve your experience with building email sending functionality:

The most popular frameworks are:

    , which offers a simple interface for email sending— Flask Mail. Feel free to learn more in our guide on how to send emails with Flask. can be a great option for building HTML templates. Also, take a look at our Django email sending tutorial. comes in handy for website development. is a dedicated mail delivery framework adding various helpful configurations. lotly and its Dash can help with mailing graphs and reports.

Good luck, and don’t forget to stay on the safe side when sending your emails!

Отправка писем в Python с помощью SMTP

Esther Vaati

Esther Vaati Last updated Mar 23, 2022

Russian (Pусский) translation by Ilya Nikov (you can also view the original English article)

В этом руководстве вы познакомитесь с SMTP, модулем Python, используемым для отправки почты. Также будет продемонстрировано, как отправлять различные типы электронных писем, такие как простые текстовые электронные письма, электронные письма с вложениями и электронные письма с содержимым HTML.

Введение в SMTP

Протокол SMTP (Simple Mail Transfer Protocol) обрабатывает отправку и маршрутизацию электронной почты между почтовыми серверами.

В Python модуль smtplib определяет объект сеанса клиента SMTP, который можно использовать для отправки почты на любой компьютер Интернета с демоном прослушивателя SMTP или ESMTP.

Вот как создать объект SMTP.

Создаём и отправляем простое электронное письмо

Следующий скрипт позволит вам отправить электронное письмо через SMTP-сервер Gmail. Тем не менее, Google не разрешит вход через smtplib , поскольку этот тип входа помечен как «менее безопасный». Чтобы решить эту проблему, перейдите на страницу https://www.google.com/settings/security/lesssecureapps, когда вы вошли в свою учетную запись Google, и «Разрешить менее безопасные приложения». Смотрите скриншот ниже.

Create and Send a Simple EmailCreate and Send a Simple Email Create and Send a Simple Email

Мы выполним следующие шаги для выполнения этого процесса:

  • Создайте объект SMTP для подключения к серверу.
  • Войдите в свою учетную запись.
  • Определите заголовки сообщений и учетные данные для входа.
  • Создайте объект сообщения MIMEMultipart и присоедините к нему соответствующие заголовки, т. е. From, To и Subject.
  • Прикрепить сообщение к сообщению MIMEMultipart объекта.
  • Наконец, отправьте сообщение.

Этот процесс очень прост, как показано ниже.

Обратите внимание, что адреса «Кому» и «От» должны быть явно включены в заголовки сообщения.

Создаём и отправляем электронное письмо с приложением

В этом примере мы собираемся отправить электронное письмо с вложенным изображением. Процесс аналогичен отправке простого текстового электронного письма.

  • Создайте объект SMTP для подключения к серверу.
  • Войдите в свою учетную запись.
  • Определите заголовки сообщений и учетные данные для входа.
  • Создайте объект сообщения MIMEMultipart и присоедините к нему соответствующие заголовки, т. е. From, To и Subject.
  • Прочитайте и приложите изображение к сообщению объекта MIMEMultipart .
  • Наконец, отправьте сообщение.

Класс MIMEImage является подклассом MIMENonMultipart , который используется для создания объектов сообщений MIME типов изображений. Другие доступные классы включают
MIMEMessage и MIMEAudio .

Создание и отправка сообщений электронной почты в формате HTML

Первое, что мы собираемся сделать, это создать шаблон электронной почты в формате HTML.

Создать шаблон HTML

Вот код HTML для шаблона, и он содержит два столбца таблицы, каждый с изображением и содержимым предварительного просмотра. Если вы предпочитаете готовое профессиональное решение, воспользуйтесь нашими лучшими почтовыми шаблонами. У нас есть несколько адаптивных опций с легко настраиваемыми функциями, с которых можно начать.

Шаблон будет выглядеть примерно так:

The HTML TemplateThe HTML Template The HTML Template

Ниже приведен скрипт для отправки электронного письма с HTML-контентом. Содержимое шаблона будет нашим почтовым сообщением.

Выполните ваш код, и если ошибки не возникнет, значит, письмо успешно отправлено. Теперь перейдите в папку «Входящие», и вы должны увидеть своё электронное письмо в виде HTML-контента, красиво отформатированного.

Formatted HTML emailFormatted HTML email Formatted HTML email

Заключение

Этот учебник охватывает большую часть того, что необходимо для отправки электронных писем для вашего приложения. Для отправки электронной почты доступно несколько API, поэтому вам не нужно начинать с нуля, например, SendGrid, но также важно понимать основы. Для получения дополнительной информации посетите документацию Python.

Кроме того, не стесняйтесь посмотреть, что у нас есть для продажи и для обучения на Envato Market, и, пожалуйста, задавайте любые вопросы и оставляйте ценные отзывы, используя канал ниже.

Читать:
Как перенести почту outlook на другой компьютер

Related Posts