1. Code
  2. Python

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

Scroll to top

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.

1
import smtplib
2
3
server = smtplib.SMTP(host='host_address',port=your_port)

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

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

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

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

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

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

1
# import necessary packages

2
3
from email.mime.multipart import MIMEMultipart
4
from email.mime.text import MIMEText
5
import smtplib
6
7
# create message object instance

8
msg = MIMEMultipart()
9
10
11
message = "Thank you"
12
13
# setup the parameters of the message

14
password = "your_password"
15
msg['From'] = "your_address"
16
msg['To'] = "to_address"
17
msg['Subject'] = "Subscription"
18
19
# add in the message body

20
msg.attach(MIMEText(message, 'plain'))
21
22
#create server

23
server = smtplib.SMTP('smtp.gmail.com: 587')
24
25
server.starttls()
26
27
# Login Credentials for sending the mail

28
server.login(msg['From'], password)
29
30
31
# send the message via the server.

32
server.sendmail(msg['From'], msg['To'], msg.as_string())
33
34
server.quit()
35
36
print "successfully sent email to %s:" % (msg['To'])

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

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

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

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

2
# import necessary packages

3
from email.mime.multipart import MIMEMultipart
4
from email.MIMEImage import MIMEImage
5
from email.mime.text import MIMEText
6
import smtplib
7
8
# create message object instance

9
msg = MIMEMultipart()
10
11
12
# setup the parameters of the message

13
password = "your_password"
14
msg['From'] = "your_address"
15
msg['To'] = "to_address"
16
msg['Subject'] = "Photos"
17
18
# attach image to message body

19
msg.attach(MIMEImage(file("google.jpg").read()))
20
21
22
# create server

23
server = smtplib.SMTP('smtp.gmail.com: 587')
24
25
server.starttls()
26
27
# Login Credentials for sending the mail

28
server.login(msg['From'], password)
29
30
31
# send the message via the server.

32
server.sendmail(msg['From'], msg['To'], msg.as_string())
33
34
server.quit()
35
36
print "successfully sent email to %s:" % (msg['To'])
37

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

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

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

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

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

1
<html>
2
<head>
3
   
4
   <title>Tutsplus Email Newsletter</title>
5
   <style type="text/css">
6
    a {color: #d80a3e;}
7
  body, #header h1, #header h2, p {margin: 0; padding: 0;}
8
  #main {border: 1px solid #cfcece;}
9
  img {display: block;}
10
  #top-message p, #bottom p {color: #3f4042; font-size: 12px; font-family: Arial, Helvetica, sans-serif; }
11
  #header h1 {color: #ffffff !important; font-family: "Lucida Grande", sans-serif; font-size: 24px; margin-bottom: 0!important; padding-bottom: 0; }
12
  #header p {color: #ffffff !important; font-family: "Lucida Grande", "Lucida Sans", "Lucida Sans Unicode", sans-serif; font-size: 12px;  }
13
  h5 {margin: 0 0 0.8em 0;}
14
    h5 {font-size: 18px; color: #444444 !important; font-family: Arial, Helvetica, sans-serif; }
15
  p {font-size: 12px; color: #444444 !important; font-family: "Lucida Grande", "Lucida Sans", "Lucida Sans Unicode", sans-serif; line-height: 1.5;}
16
   </style>
17
</head>
18
<body>
19
<table width="100%" cellpadding="0" cellspacing="0" bgcolor="e4e4e4"><tr><td>
20
<table id="top-message" cellpadding="20" cellspacing="0" width="600" align="center">
21
    <tr>
22
      <td align="center">
23
        <p><a href="#">View in Browser</a></p>
24
      </td>
25
    </tr>
26
  </table>
27
28
<table id="main" width="600" align="center" cellpadding="0" cellspacing="15" bgcolor="ffffff">
29
    <tr>
30
      <td>
31
        <table id="header" cellpadding="10" cellspacing="0" align="center" bgcolor="8fb3e9">
32
          <tr>
33
            <td width="570" align="center"  bgcolor="#d80a3e"><h1>Evanto Limited</h1></td>
34
          </tr>
35
          <tr>
36
            <td width="570" align="right" bgcolor="#d80a3e"><p>November 2017</p></td>
37
          </tr>
38
        </table>
39
      </td>
40
    </tr>
41
42
    <tr>
43
      <td>
44
        <table id="content-3" cellpadding="0" cellspacing="0" align="center">
45
          <tr>
46
              <td width="250" valign="top" bgcolor="d0d0d0" style="padding:5px;">
47
              <img src="https://thumbsplus.tutsplus.com/uploads/users/30/posts/29520/preview_image/pre.png" width="250" height="150"  />
48
            </td>
49
              <td width="15"></td>
50
            <td width="250" valign="top" bgcolor="d0d0d0" style="padding:5px;">
51
                <img src="https://cms-assets.tutsplus.com/uploads/users/30/posts/29642/preview_image/vue-2.png" width ="250" height="150" />
52
            </td>
53
          </tr>
54
        </table>
55
      </td>
56
    </tr>
57
    <tr>
58
      <td>
59
        <table id="content-4" cellpadding="0" cellspacing="0" align="center">
60
          <tr>
61
            <td width="200" valign="top">
62
              <h5>How to Get Up and Running With Vue</h5>
63
              <p>In the introductory post for this series we spoke a little about how web designers can benefit by using Vue. In this tutorial we’ll learn how to get Vue up..</p>
64
            </td>
65
            <td width="15"></td>
66
            <td width="200" valign="top">
67
              <h5>Introducing Haiku: Design and Create Motion</h5>
68
              <p>With motion on the rise amongst web developers so too are the tools that help to streamline its creation. Haiku is a stand-alone..</p>
69
            </td>
70
          </tr>
71
        </table>
72
      </td>
73
    </tr>
74
  </table>
75
  <table id="bottom" cellpadding="20" cellspacing="0" width="600" align="center">
76
    <tr>
77
      <td align="center">
78
        <p>Design better experiences for web & mobile</p>
79
        <p><a href="#">Unsubscribe</a> | <a href="#">Tweet</a> | <a href="#">View in Browser</a></p>
80
      </td>
81
    </tr>
82
  </table><!-- top message -->
83
</td></tr></table><!-- wrapper -->
84
85
</body>
86
</html>

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

The HTML TemplateThe HTML TemplateThe HTML Template

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

1
import smtplib
2
import email.message
3
server = smtplib.SMTP('smtp.gmail.com:587')
4
5
email_content = """

6
<html>

7


8
<head>

9
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

10
   

11
   <title>Tutsplus Email Newsletter</title>

12
   <style type="text/css">

13
    a {color: #d80a3e;}

14
  body, #header h1, #header h2, p {margin: 0; padding: 0;}

15
  #main {border: 1px solid #cfcece;}

16
  img {display: block;}

17
  #top-message p, #bottom p {color: #3f4042; font-size: 12px; font-family: Arial, Helvetica, sans-serif; }

18
  #header h1 {color: #ffffff !important; font-family: "Lucida Grande", sans-serif; font-size: 24px; margin-bottom: 0!important; padding-bottom: 0; }

19
  #header p {color: #ffffff !important; font-family: "Lucida Grande", "Lucida Sans", "Lucida Sans Unicode", sans-serif; font-size: 12px;  }

20
  h5 {margin: 0 0 0.8em 0;}

21
    h5 {font-size: 18px; color: #444444 !important; font-family: Arial, Helvetica, sans-serif; }

22
  p {font-size: 12px; color: #444444 !important; font-family: "Lucida Grande", "Lucida Sans", "Lucida Sans Unicode", sans-serif; line-height: 1.5;}

23
   </style>

24
</head>

25


26
<body>

27


28


29
<table width="100%" cellpadding="0" cellspacing="0" bgcolor="e4e4e4"><tr><td>

30
<table id="top-message" cellpadding="20" cellspacing="0" width="600" align="center">

31
    <tr>

32
      <td align="center">

33
        <p><a href="#">View in Browser</a></p>

34
      </td>

35
    </tr>

36
  </table>

37


38
<table id="main" width="600" align="center" cellpadding="0" cellspacing="15" bgcolor="ffffff">

39
    <tr>

40
      <td>

41
        <table id="header" cellpadding="10" cellspacing="0" align="center" bgcolor="8fb3e9">

42
          <tr>

43
            <td width="570" align="center"  bgcolor="#d80a3e"><h1>Evanto Limited</h1></td>

44
          </tr>

45
          <tr>

46
            <td width="570" align="right" bgcolor="#d80a3e"><p>November 2017</p></td>

47
          </tr>

48
        </table>

49
      </td>

50
    </tr>

51


52
    <tr>

53
      <td>

54
        <table id="content-3" cellpadding="0" cellspacing="0" align="center">

55
          <tr>

56
              <td width="250" valign="top" bgcolor="d0d0d0" style="padding:5px;">

57
              <img src="https://thumbsplus.tutsplus.com/uploads/users/30/posts/29520/preview_image/pre.png" width="250" height="150"  />

58
            </td>

59
              <td width="15"></td>

60
            <td width="250" valign="top" bgcolor="d0d0d0" style="padding:5px;">

61
                <img src="https://cms-assets.tutsplus.com/uploads/users/30/posts/29642/preview_image/vue-2.png" width ="250" height="150" />

62
            </td>

63
          </tr>

64
        </table>

65
      </td>

66
    </tr>

67
    <tr>

68
      <td>

69
        <table id="content-4" cellpadding="0" cellspacing="0" align="center">

70
          <tr>

71
            <td width="200" valign="top">

72
              <h5>How to Get Up and Running With Vue</h5>

73
              <p>In the introductory post for this series we spoke a little about how web designers can benefit by using Vue. In this tutorial we will learn how to get Vue up..</p>

74
            </td>

75
            <td width="15"></td>

76
            <td width="200" valign="top">

77
              <h5>Introducing Haiku: Design and Create Motion</h5>

78
              <p>With motion on the rise amongst web developers so too are the tools that help to streamline its creation. Haiku is a stand-alone..</p>

79
            </td>

80
          </tr>

81
        </table>

82
      </td>

83
    </tr>

84
    

85


86
  </table>

87
  <table id="bottom" cellpadding="20" cellspacing="0" width="600" align="center">

88
    <tr>

89
      <td align="center">

90
        <p>Design better experiences for web & mobile</p>

91
        <p><a href="#">Unsubscribe</a> | <a href="#">Tweet</a> | <a href="#">View in Browser</a></p>

92
      </td>

93
    </tr>

94
  </table><!-- top message -->

95
</td></tr></table><!-- wrapper -->

96


97
</body>

98
</html>

99


100


101
"""
102
103
msg = email.message.Message()
104
msg['Subject'] = 'Tutsplus Newsletter'
105
106
107
msg['From'] = 'youraddress'
108
msg['To'] = 'to_address'
109
password = "yourpassword"
110
msg.add_header('Content-Type', 'text/html')
111
msg.set_payload(email_content)
112
113
s = smtplib.SMTP('smtp.gmail.com: 587')
114
s.starttls()
115
116
# Login Credentials for sending the mail

117
s.login(msg['From'], password)
118
119
s.sendmail(msg['From'], [msg['To']], msg.as_string())

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

Formatted HTML emailFormatted HTML emailFormatted HTML email

Заключение

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

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