In [1]:
import smtplib
In [2]:
#for gmail
with smtplib.SMTP('smtp.gmail.com',587) as smtp:
    smtp.ehlo() #indentifies ourself with mailserver
    smtp.starttls()  #encrypting the traffic
    smtp.ehlo()  #reidentify ourself as encrpyted connection
    
    smtp.login('kushagra225@gmail.com','password')
    subject = 'hello'
    body = 'sample body'
    msg = f'Subject: {subject}\n\n{body}'
    
    #smtp.sendmail(Sender,receiver,msg)
    smtp.sendmail('kushagra225@gmail.com','kushagra224@gmail.com',msg)
In [ ]:
#for testing you can also use local debug on terminal 
!python3 -m smtpd -c DebuggingServer -n localhost:1025
In [2]:
#in python
with smtplib.SMTP('localhost',1026) as smtp:

    subject = 'hello'
    body = 'sample body'
    msg = f'Subject: {subject}\n\n{body}'
In [5]:
#simpler with SMTP_SSL
with smtplib.SMTP_SSL('smtp.gmail.com',465) as smtp:
    smtp.login('kushagra225@gmail.com','xyksfkwxgihjkkxo')
    
    subject = 'hello'
    body = 'sample body'
    msg = f'Subject: {subject}\n\n{body}'

    smtp.sendmail('kushagra225@gmail.com','kushagra224@gmail.com',msg)
In [8]:
#more readable using email.message
import smtplib
from email.message import EmailMessage

msg = EmailMessage()
msg['Subject'] = 'Sample Subject'
msg['From'] = 'kushagra225@gmail.com'
msg['To'] = 'kushagra224@gmail.com'
msg.set_content('sample body message')

with smtplib.SMTP_SSL('smtp.gmail.com',465) as smtp:
    smtp.login('kushagra225@gmail.com','password')

    smtp.send_message(msg)
In [13]:
#sending attachment
import smtplib
from email.message import EmailMessage
import imghdr

msg = EmailMessage()
msg['Subject'] = 'Image of puppy'
msg['From'] = 'kushagra225@gmail.com'
msg['To'] = 'kushagra224@gmail.com'
msg.set_content('image attached')

with open('golden.jpg','rb') as f:
    file_data = f.read()
    #to know format of image
    file_name =f.name
    file_type = imghdr.what(file_name)
    
msg.add_attachment(file_data, maintype='image',subtype=file_type, filename=file_name)
    
with smtplib.SMTP_SSL('smtp.gmail.com',465) as smtp:
    smtp.login('kushagra225@gmail.com','password')

    smtp.send_message(msg)
In [15]:
#sending pdf attachment
import smtplib
from email.message import EmailMessage
import imghdr

msg = EmailMessage()
msg['Subject'] = 'resume'
msg['From'] = 'kushagra225@gmail.com'
msg['To'] = 'kushagra224@gmail.com'
msg.set_content('image attached')

files = ['resume.pdf']

for file in files:
    with open(file,'rb') as f:
        file_data = f.read()
        #to know format of image
        file_name =f.name

    msg.add_attachment(file_data, maintype='application',subtype='octet-stream', filename=file_name)

with smtplib.SMTP_SSL('smtp.gmail.com',465) as smtp:
    smtp.login('kushagra225@gmail.com','password')

    smtp.send_message(msg)