1. Code
  2. Python

Mengirim Email di Python dengan SMTP

Scroll to top

Indonesian (Bahasa Indonesia) translation by Bagus Aji Santoso (you can also view the original English article)

Tutorial ini akan mengenalkan SMTP, sebuah modul Python untuk mengirim email. Tutorial ini juga akan menunjukkan bagaimana mengirim tipe email yang berbeda seperti email teks sederhana, email dengan attachment, dan email dengan konten HTML.

Perkenalan SMTP

Simple Mail Transfer Protocol (SMTP) menangani proses pengiriman dan routing email antar mail server.

Di Python, modul smtplib menentukan objek client session SMTOP yang dapat dipakai untuk mengirim email ke mesin Internet manapun yang memiliki listener daemon SMTP atau ESMTP.

Begini bagaimana cara membuat objek SMTP.

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

Membuat dan Mengirim Email Sederhana

Skrip berikut ini akan memungkinkan kita untuk mengirim sebuah email lewat server SMTP Gmail. Namun, Google tidak akan memperbolehkan kita untuk melakukan login via smtplib karena teknik login ini sudah ditandai sebagai "teknik yang kurang aman".  Untuk mengatasi permasalahan ini, buka link https://www.google.com/settings/security/lesssecureapps setelah melakukan login ke akun Google anda, lalu klik "Allow less secure apps". Lihat tangkapan layar di bawah.

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

Kita akan mengikuti langkah-langkah berikut untuk mencapai tujuan kita:

  • Buat sebuah objek SMTP untuk membuat koneksi ke server.
  • Log in ke akun kita.
  • Tentukan header pesan dan infomasi login.
  • Buat sebuah objek pesan bertipe MIMEMultipart dan tambahkan header yang relevan misalnya From, To, dan Subject.
  • Tempelkan pesan ke objek MIMEMultipart.
  • Terakhir, kirim pesannya.

Proses sederhana ini dapat terlihat pada kode di bawah.

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'])

Perhatikan bahwa  alamat 'To' dan 'From' harus ditambahkan di header pesan secara eksplisit.

Membuat dan Mengirim Email dengan sebuah Attachment

Pada contoh ini, kita akan mengirim sebuah email dengan sebuah attachment gambar. Proses ini mirip dengan mengirim email sederhana.

  • Buat sebuah objek SMTP untuk koneksi ke server.
  • Log in ke akun kita. 
  • Tentukan header pesan dan informasi login. 
  • Buat objek pesan MIMEMultipart dan tambahkan header yang relevan misalnya From, TO, dan Subject.
  • Baca dan tambahkan gambar ke objek pesan MIMEMultipart.
  • Terakhir, kirim pesannya. 
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

Kelas MIMEImage adalah subclass dari MIMENonMultipart yang digunakan untuk membuat objek pesan MIME dengan tipe image. Kelas lain yang tersedia adalah:
MIMEMessage dan MIMEAudio.

Membuat dan Mengirim Email HTML

Hal pertama yang akan kita buat adalah membuat template email HTML-nya.

Membuat Sebuah Template HTML

Berikut kode HTML untuk template yang memiliki tabel dengan dua kolom dimana disetiap kolomnya memiliki sebuah gambar dan konten preview. Jika ingin menggunakan solusi profesional yang siap pakai, gunakan salah satu template email terbaik kami. Kami memiliki banyak opsi yang mudah untuk dipakai dan diatur ulang isinya sebagai template awal.

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>

Template ini akan terlihat sebagai berikut setelah jadi:

The HTML TemplateThe HTML TemplateThe HTML Template

Di bawah ini merupakan skrip untuk mengirim sebuah email dengan konten HTML. Isi template tadi akan menjadi pesan email kita. 

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())

Jalankan kode kita dan apabila tidak ada error yang muncul berarti email berhasil dikirim. Sekarang buka inbox dan seharusnya sudh ada email dengan konten HTML yang cantik. 

Formatted HTML emailFormatted HTML emailFormatted HTML email

Kesimpulan

Tutorial ini sudah membahas apa-apa saja yang dibutuhkan untuk mengirim email dari aplikasi yang kita buat.  Ada beberapa API yang tersedia untuk mengirim email sehingga kita tidak perlu membangun dari awal seperti SendGrid, tapi memahami dasar-dasarnya juga penting. Untuk informasi lebih lanjut kunjungi dokumentasi Python

Sebagai tambahan, jangan sungkan untuk melihat koleksi kami yang siap pakai di Envator Market, serta jangan malu untuk mengirimkan pertanyaan atau umpan balik melalui kolom di bawah ini.