Created
January 9, 2012 10:49
-
-
Save cou929/1582468 to your computer and use it in GitHub Desktop.
Send mail via GMail smtp.
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
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
import smtplib | |
import sys | |
import os | |
from email.MIMEText import MIMEText | |
from email.Utils import formatdate | |
from email.Header import Header | |
from optparse import OptionParser | |
def create_message(mailfrom, mailto, subject, body): | |
msg = MIMEText(unicode(body, 'utf-8').encode('iso-2022-jp'), | |
_charset='iso-2022-jp') | |
msg['Subject'] = Header(unicode(subject, 'utf-8').encode('iso-2022-jp'), | |
'iso-2022-jp') | |
msg['From'] = mailfrom | |
msg['To'] = mailto | |
msg['Date'] = formatdate() | |
return msg | |
def send_via_gmail(mailfrom, mailto, msg, loginid, password): | |
s = smtplib.SMTP('smtp.gmail.com', 587) | |
s.ehlo() | |
s.starttls() | |
s.ehlo() | |
s.login(loginid, password) | |
s.sendmail(mailfrom, mailto, msg.as_string()) | |
s.close() | |
def parse_options(): | |
parser = OptionParser(usage='%prog [-s SUBJECT] MAIL_TO < MAIL_BODY') | |
parser.add_option("-s", "--subject", type="string", | |
dest="subject", default='', help="Mail subject") | |
parser.add_option("-f", "--mailfrom", type="string", | |
dest="mailfrom", default='[email protected]', | |
help="Mail from") | |
(options, args) = parser.parse_args() | |
if len(args) < 1: | |
parser.print_help() | |
exit(1) | |
return (options, args) | |
if __name__ == '__main__': | |
(options, args) = parse_options() | |
if not os.environ.has_key('GM_LOGINID') or not os.environ.has_key('GM_PASSWORD'): | |
sys.stderr.write('\n'.join(['No login username or password.', | |
'Set env GM_LOGINID and GM_PASSWORD.\n'])) | |
exit(2) | |
loginid = os.environ['GM_LOGINID'] | |
password = os.environ['GM_PASSWORD'] | |
mailfrom = options.mailfrom | |
mailto = args | |
subject = options.subject | |
body = sys.stdin.read() | |
send_via_gmail(mailfrom, mailto, | |
create_message(mailfrom, ','.join(mailto), subject, body), | |
loginid, password) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment