Created
October 10, 2019 19:31
-
-
Save silgon/a24e9548eacae46a542ca6c8255f9baf to your computer and use it in GitHub Desktop.
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
# based on: | |
# https://stackoverflow.com/a/882770/2237916 | |
# https://stackoverflow.com/a/53970596/2237916 | |
import smtplib | |
from email.mime.application import MIMEApplication | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
from os.path import basename | |
# me == my email address | |
# you == recipient's email address | |
me = "myself@mail.com" | |
you = "destinatary@mail.com" | |
# Create message container - the correct MIME type is multipart/alternative. | |
# msg = MIMEMultipart('alternative') | |
# msg = MIMEMultipart('mixed') | |
msg = MIMEMultipart('mixed') | |
msg['Subject'] = "Link" | |
msg['From'] = "My Name <{}>".format(me) | |
msg['To'] = you | |
# Create the body of the message (a plain-text and an HTML version). | |
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org" | |
html = """\ | |
<html> | |
<head></head> | |
<body> | |
<p>Hi!<br> | |
How are you?<br> | |
Here is the <a href="http://www.python.org">link</a> you wanted. | |
</p> | |
</body> | |
</html> | |
""" | |
# Record the MIME types of both parts - text/plain and text/html. | |
part1 = MIMEText(text, 'plain') | |
part2 = MIMEText(html, 'html') | |
# Attach parts into message container. | |
# According to RFC 2046, the last part of a multipart message, in this case | |
# the HTML message, is best and preferred. | |
msg_ = MIMEMultipart('alternative') | |
msg_.attach(part1) | |
msg_.attach(part2) | |
msg.attach(msg_) | |
f="image.png" | |
with open(f, "rb") as fil: | |
part = MIMEApplication( | |
fil.read(), | |
Name=basename(f) | |
) | |
# After the file is closed | |
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f) | |
msg.attach(part) | |
#Ports 465 and 587 are intended for email client to email server communication - sending email | |
server = smtplib.SMTP('mail.server.com', 587) | |
#starttls() is a way to take an existing insecure connection and upgrade it to a secure connection using SSL/TLS. | |
server.starttls() | |
#Next, log in to the server | |
server.login("login_user@mail.com", "login_password") | |
server.sendmail(me, you, msg.as_string()) | |
server.quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment