List

Tutorial berikut ini akan mengulas kode singkat menggunakan Python 3 untuk mengirim email. Kita akan menggunakan paket smtplib, ssl. Langkah yang pertama adalah instalasi smtplib menggunakan PIP

pip install secure-smtplib

langkah berikutnya adalah install paket ssl menggunakan PIP

pip install ssl

Buatlah kode sederhana berikut ini, dan simpanlah dalam nama kirim_email.py

import smtplib, ssl from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart # email pengirim sender_email = "arisbd@gmail.com" # email penerima receiver_email = "arisbudianto@staff.uns.ac.id" password email password = "xxxxxx" message = MIMEMultipart("alternative") message["Subject"] = "multipart test" message["From"] = sender_email message["To"] = receiver_email attachment = '/home/aris/Project/clouds.jpg' # Pesan yang akan dikirimkan dalam email text = """\ Hi, How are you? Real Python has many great tutorials: www.realpython.com""" html = """\ <html> <body> <p>Hi,<br> How are you?<br> <a href="http://www.realpython.com">Real Python</a> has many great tutorials. <img src="/home/aris/Project/clouds.jpg"> </p> </body> </html> """ # Turn these into plain/html MIMEText objects part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") # Add HTML/plain-text parts to MIMEMultipart message # The email client will try to render the last part first message.attach(part1) message.attach(part2) fp = open(attachment, 'rb') img = MIMEImage(fp.read()) fp.close() img.add_header('Content-ID', '<{}>'.format(attachment)) message.attach(img) server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(sender_email, password) server.sendmail(sender_email, receiver_email, message.as_string()) server.quit()

Jalankan dengan perintah python send_email.py

Catatan, program bisa berjalan sebelum ada kebijakan 2 step verification di gmail, setelah itu belum di coba lagi 🙂