Last active
June 13, 2016 23:39
-
-
Save gb-swatanabe/6239546 to your computer and use it in GitHub Desktop.
mail send script with SMTP over SSL and SMTP-AUTH
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/env python | |
# -*- coding: utf-8 -*- | |
# send-mail.py - mail send script with SMTP over SSL and SMTP-AUTH | |
# usage: $0 [-n <sender name>] [-f <sender address>] <recipient address> <subject> | |
#----#----#----#----#----#----#----#----#----#----#----#----#----#----#----# | |
# 送信サーバ設定 | |
mailserver = 'mailserver.example.com:25' | |
auth_user = 'username' | |
auth_pass = 'password' | |
#----#----#----#----#----#----#----#----#----#----#----#----#----#----#----# | |
def create_message( from_addr, to_addr, subject, body, encoding ): | |
msg = MIMEText( body.encode(encoding), 'plain', encoding ) | |
msg['Subject'] = Header( subject, encoding ) | |
msg['From'] = from_addr | |
msg['To'] = "<%s>" % to_addr | |
msg['Date'] = formatdate( localtime=True ) | |
msg['Message-Id'] = make_msgid() | |
msg['X-Mailer'] = sys.argv[0] | |
return msg | |
def send_with_tls( from_addr, to_addr, msg, mailserver, auth_user, auth_pass ): | |
server = mailserver.split(':',2)[0] | |
port = mailserver.split(':',2)[1] | |
s = smtplib.SMTP( server, int(port) ) | |
s.ehlo() | |
s.starttls() | |
s.ehlo() | |
s.login( auth_user, auth_pass ) | |
s.sendmail( from_addr, [to_addr], msg.as_string() ) | |
s.close | |
if __name__ == '__main__': | |
import sys | |
import smtplib | |
from optparse import OptionParser | |
from email.MIMEText import MIMEText | |
from email.Header import Header | |
from email.Utils import formatdate | |
from email.Utils import make_msgid | |
parser = OptionParser() | |
parser.add_option("-n", "--name", dest="from_name", default='') | |
parser.add_option("-f", "--from", dest="from_addr", default='nobody') | |
(options, args) = parser.parse_args() | |
# パラメータが足りなければヘルプ出して終了 | |
if len( args ) != 2 : | |
print "Usage: %s [-n <sender name>] [-f <sender address>] <rcpient address> <subject>" % sys.argv[0] | |
print "(本文は標準入力から)" | |
quit() | |
encoding = 'ISO-2022-JP' # メール本文のエンコード指定 | |
to_addr = args[0] | |
subject = args[1] | |
sender = "%s <%s>" % ( Header( options.from_name, encoding ), options.from_addr ) | |
body = '' | |
for line in sys.stdin: | |
body += line.decode('utf-8') # STDINから本文を読取 | |
msg = create_message( sender, to_addr, subject, body, encoding ) | |
send_with_tls( options.from_addr, to_addr, msg, mailserver, auth_user, auth_pass ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
msmtpつかうほうが良い(確信