adding attachment using email module python code example
Example 1: email in python
import smtplib
from email.message import EmailMessage
EmailAdd = "Email id"
Pass = "Email Password"
msg = EmailMessage()
msg['Subject'] = 'Subject of the Email'
msg['From'] = EmailAdd
msg['To'] = '[email protected]','[email protected]'
msg.set_content('Mail Body')
with smtplib.SMTP_SSL('smtp.gmail.com',465) as smtp:
smtp.login(EmailAdd,Pass)
smtp.send_message(msg)
Example 2: how to send doc using python smtp
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
fromaddr = "EMAIL address of the sender"
toaddr = "EMAIL address of the receiver"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Subject of the Mail"
body = "Body_of_the_mail"
msg.attach(MIMEText(body, 'plain'))
filename = "File_name_with_extension"
attachment = open("Path of the file", "rb")
p = MIMEBase('application', 'octet-stream')
p.set_payload((attachment).read())
encoders.encode_base64(p)
p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(p)
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login(fromaddr, "Password_of_the_sender")
text = msg.as_string()
s.sendmail(fromaddr, toaddr, text)
s.quit()