Learning Python Network Programming

(Sean Pound) #1
Chapter 4
part = MIMEText('text', "plain")
part.set_payload(message)
msg.attach(part)
# attach an image in the current directory
filename = input('Enter the file name of a GIF image: ')
path = os.path.join(os.getcwd(), filename)
if os.path.exists(path):
img = MIMEImage(open(path, 'rb').read(), _subtype="gif")
img.add_header('Content-Disposition', 'attachment',
filename=filename)
msg.attach(img)
# create smtp session
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo
# send mail
session.sendmail(sender, recipient, msg.as_string())
print("You email is sent to {0}.".format(recipient))
session.quit()

if __name__ == '__main__':
sender = input("Enter sender email address: ")
recipient = input("Enter recipeint email address: ")
send_email(sender, recipient)

If you run the preceding script, then it will ask the usual, that is, the e-mail sender,
the recipient, the user credentials, and the location of the image file.


$ python3 smtp_mail_sender_mime.py


Enter sender email address: [email protected]


Enter recipeint email address: [email protected]


Enter your email subject: Test email with attachment


Enter your email message. Press Enter when finished. This is a test email
with atachment.


Enter the file name of a GIF image: image.gif


You email is sent to [email protected].

Free download pdf