Created
February 11, 2022 06:35
-
-
Save misgeatgit/90cc9611095eaa8c7afc6bf2b78c9324 to your computer and use it in GitHub Desktop.
Demonstration of how to send email with different types of attachments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import smtplib | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
from email.mime.image import MIMEImage | |
from email.mime.application import MIMEApplication | |
def send_test_mail(body): | |
sender_email = "misgana.bayetta@gmail.com" | |
receiver_email = "misgana.oss@gmail.com" | |
msg = MIMEMultipart() | |
msg['Subject'] = '[Email Test]' | |
msg['From'] = sender_email | |
msg['To'] = receiver_email | |
msgText = MIMEText('<b>%s</b>' % (body), 'html') | |
msg.attach(msgText) | |
filename = "example.txt" | |
txt = MIMEApplication(open(filename).read()) | |
txt.add_header('Content-Disposition', 'attachment', filename= "example.txt") | |
msg.attach(txt) | |
with open('example.jpg', 'rb') as fp: | |
img = MIMEImage(fp.read()) | |
img.add_header('Content-Disposition', 'attachment', filename="example.jpg") | |
msg.attach(img) | |
pdf = MIMEApplication(open("example.pdf", 'rb').read()) | |
pdf.add_header('Content-Disposition', 'attachment', filename= "example.pdf") | |
msg.attach(pdf) | |
try: | |
with smtplib.SMTP('smtp.gmail.com', 587) as smtpObj: | |
smtpObj.ehlo() | |
smtpObj.starttls() | |
smtpObj.login("misgana.bayetta@gmail.com", "GENERATED_PASSWORD") | |
#go to accounts/security and generate password for the device you are running on | |
smtpObj.sendmail(sender_email, receiver_email, msg.as_string()) | |
except Exception as e: | |
print(e) | |
send_test_mail("A test email from a python script.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment