Last active
May 7, 2018 14:23
-
-
Save felipefpx/c4d2ddb95e8e2d669251966ac5819f16 to your computer and use it in GitHub Desktop.
This code sends an email with attachments using Python
This file contains hidden or 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 | |
import sys | |
from os.path import basename | |
from email.mime.application import MIMEApplication | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
from email.utils import COMMASPACE, formatdate | |
# Usage: python send_email.py "[email protected]" "pass" "[email protected], [email protected]" "DEV" "ADT" "v1.2.3" "/Users/username/Desktop/log.txt,/Users/username/Desktop/dolog.txt" | |
send_from = sys.argv[1] | |
password = sys.argv[2] | |
send_to = sys.argv[3].split(',') | |
branch = sys.argv[4] | |
projectName = sys.argv[5] | |
version = sys.argv[6] | |
files=sys.argv[7].split(",") | |
server="smtp.gmail.com:587" | |
msg = MIMEMultipart('alternative') | |
msg['From'] = send_from | |
msg['To'] = ', '.join(send_to) | |
msg['Date'] = formatdate(localtime=True) | |
msg['Subject'] = "[%s] %s - BUILD SUCCEEDED - %s" % (branch, projectName, version) | |
html = """\ | |
<html> | |
<head> | |
<title>BUILD SUCCEEDED</title> | |
</head> | |
<body> | |
<h1>Fractal Tecnologia</h1> | |
<h3>Android CI/CD - Shippable</h3> | |
<br/> | |
<ul> | |
<li><b>Project: %s</li> | |
<li><b>Branch: %s</li> | |
<li><b>Version:</b> %s</li> | |
</ul> | |
</body> | |
</html> | |
""" % ( projectName, branch, version ) | |
print "====\nPreparing attachments...\n====" | |
msg.attach(MIMEText(html, 'html')) | |
for f in files or []: | |
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) | |
print "====\nSending to %s...\n\n%s\nAttachments: " % (send_to, html) | |
print files | |
print "\n====" | |
server = smtplib.SMTP(server) | |
server.ehlo() | |
server.starttls() | |
server.login(send_from, password) | |
server.sendmail(send_from, send_to, msg.as_string()) | |
server.quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment