Skip to content

Sending Email with Python

🗓 June 6th, 2022

Before you send email from pyhon script, you should know that sending by email means you have to enter your credentials into your python script. So that means its' dangerous right? luckily google had taken care of that problem, google gives access to get login without actual password, so google will just make generated password in certain activity(email/callendar/etc).

so to make it clear, you can check how to make grant app google credential in this link (use it wisely, make sure no one knows your generated password)

after waching that video, you will have 16 generated password that you can use to login from your app

import smtplib
from email.mime.text import MIMEText

smtp_ssl_host = 'smtp.gmail.com'
smtp_ssl_port = 465
email = 'your_email@gmail.com'
password = '<16_generated_password>'
sender = email
targets = ['receiver@gmail.com']

msg = MIMEText('Hi, how are you today?')
msg['Subject'] = 'Hello'
msg['From'] = sender
msg['To'] = ', '.join(targets)

server = smtplib.SMTP_SSL(smtp_ssl_host, smtp_ssl_port)
server.login(email, password)
server.sendmail(sender, targets, msg.as_string())
server.quit()
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

smtp_ssl_host = 'smtp.gmail.com'  # smtp.mail.yahoo.com
smtp_ssl_port = 465
email = 'your_email@gmail.com'
password = '<16_generated_password>'
sender = email
targets = ['receiver@gmail.com']

msg = MIMEMultipart()
msg['Subject'] = 'I have a picture'
msg['From'] = sender
msg['To'] = ', '.join(targets)

txt = MIMEText('I just bought a new camera.')
msg.attach(txt)

filepath = './file.txt'
with open(filepath, 'r') as f:
    file_att = MIMEText(f.read())
# filepath_img = './file.jpg'
# with open(filepath_img, 'rb') as f:
    # file_att = MIMEImage(f.read())

file_att.add_header('Content-Disposition',
            'attachment',
            filename=os.path.basename(filepath))
msg.attach(file_att)

server = smtplib.SMTP_SSL(smtp_ssl_host, smtp_ssl_port)
server.login(username, password)
server.sendmail(sender, targets, msg.as_string())
server.quit()
$ python <file_name.py>

that's all, check your mail box