Skip to content

Instantly share code, notes, and snippets.

@thilinapiy
Created June 15, 2012 17:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thilinapiy/2937681 to your computer and use it in GitHub Desktop.
Save thilinapiy/2937681 to your computer and use it in GitHub Desktop.
My Python e-mail script
#!/usr/bin/python
import smtplib
import getpass
import base64
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.MIMEBase import MIMEBase
from email.Utils import COMMASPACE, formatdate
from email import Encoders
def send_a_mail(sender, password, receiver, subject, file, text, html):
try :
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# msg.attach(part1)
msg.attach(part2)
# Add atachment
if file != "":
part3 = MIMEBase('application', "octet-stream")
part3.set_payload( open(file,"rb").read() )
Encoders.encode_base64(part3)
part3.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
msg.attach(part3)
# Send the message via local SMTP server.
# This is for Gmail.
s = smtplib.SMTP('smtp.gmail.com', 587)
print "Mail created successfully."
except Exception as e :
print e
sys.exit()
try :
print "Login to the mail server."
s.ehlo()
s.starttls()
s.ehlo()
s.login(sender,password)
s.sendmail(sender, receiver, msg.as_string())
s.quit()
print "Mail send successfully."
except Exception as e :
print e
sender = raw_input('Senders mail : ')
password = getpass.getpass('Password : ')
receiver = raw_input('Receiver : ')
subject = raw_input('Subject : ')
attachment = raw_input('Full path to the attachment or press "Enter" to ignore) : ')
text = """\
Put your text message here to use by mail clients that does not support HTML e-mail.
"""
html = """\
<html>
<head>
<style type="text/css" >
* {
margin:0;
padding:0;
border:0;
}
</style>
</head>
<body style="text-align:center;">
<h2>Your html message comes here.</h2>
</body>
</html>
"""
send_a_mail(sender, password, receiver, subject, attachment, text, html)
@thilinapiy
Copy link
Author

Some e-mail clients like yahoo have problems with attachments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment