pythonスクリプトでGMailからメールする
http://labs.unoh.net/2007/06/python_2.htmlを参考にしました。
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This module allows you to send gmail from python script. Usage: mail = MyMail(from_addr, to_addr, subject) mail.create_message(msg) mail.send_gmail() """ import getpass import smtplib from email.MIMEText import MIMEText from email.Header import Header from email.Utils import formatdate class MyMail(object): def __init__(self, from_addr, to_addr, subject): if from_addr.split('@')[-1] == 'gmail.com': self.pwd = getpass.getpass('Enter your password: ') self.from_addr = from_addr self.to_addr = to_addr self.subject = subject def create_message(self, body='', encoding='utf-8'): # create a MIME text like: 'text/plain; charset="encoding"' self.msg = MIMEText(body, 'plain', encoding) self.msg['Subject'] = Header(self.subject, encoding) self.msg['From'] = self.from_addr self.msg['To'] = self.to_addr self.msg['Date'] = formatdate() def send_gmail(self): s = smtplib.SMTP('smtp.gmail.com', 587) s.ehlo() s.starttls() s.ehlo() s.login(self.from_addr, self.pwd) s.sendmail(self.from_addr, [self.to_addr], str(self.msg)) s.close() if __name__ == '__main__': import sys from_addr = 'your_mail_address@gmail.com' to_addr = from_addr subject = 'Sent by python script' msg = '' for arg in sys.argv[1:]: if 'from=' in arg: from_addr = arg.split('=')[-1] elif 'to=' in arg: to_addr = arg.split('=')[-1] elif 'subject=' in arg: subject = arg.split('=')[-1] elif 'msg=' in arg: msg = arg.split('=')[-1] mail = MyMail(from_addr, to_addr, subject) mail.create_message(msg) mail.send_gmail() print 'sent message.'
argvの取得下手すぎる。もっとスマートなやり方絶対あるw
GMailにログインするのにパスワードを入力する必要があるが、丸見えでは恥ずかしいので入力を隠したい。
これには、getpassモジュールをインポートし、getpass.getpass()を使えばおk。
問題は、utf-8指定しているけれどコマンドラインから日本語引数渡すと受信メールが文字化けしてしまうこと。
encode, decode, unicodeも使ってみたがエラー出る。
原因が良く分からないし、実際あまり日本語文送る用途で用いるつもりはないのでおkとしておく(ぇ
また、コマンドラインだと日本語使いにくいってのもある。