sendmailで日本語メールを送信する日本語をISO-2022-JPにエンコードする.ISO-2022-JPに存在していないいくつかのコードを置換するのが重要である.codesendmailjp.py←右クリックで保存できます.#!/usr/bin/env python #coding: utf-8 import os from email.MIMEText import MIMEText from email.Message import Message from email.Header import Header ################################################################ def uniuni(str): list = [\ [u'\uFF5E', u'\u301C'], # '~'→'〜' \ [u'\u2225', u'\u2016'], # '∥'→'‖' \ [u'\uFF0d', u'\u2212'], # '-'→'−' \ [u'\uFFE0', u'\u00A2'], # '¢'→'¢' \ [u'\uFFE1', u'\u00A3'], # '£'→'£' \ [u'\uFFE2', u'\u00Ac'], # '¬'→'¬' \ ] for lt in list: str = str.replace( lt[0], lt[1] ) return str ################################################################ def sendmailjp(mailto = '', mailcc = '', mailbcc = '', mailfrom = '', mailsubject = '', mailbody = '', sendmailpath = '/usr/sbin/sendmail' ): mailsubject = uniuni(mailsubject) mailbody = uniuni(mailbody) msg = MIMEText(mailbody.encode('ISO-2022-JP'), 'plain', 'ISO-2022-JP') status = 'NG' if( mailfrom != '' and mailto != '' ): msg['From'] = mailfrom msg['To'] = mailto if( mailcc != '' ): msg['Cc'] = mailcc if( mailbcc != '' ): msg['Bcc'] = mailbcc msg['Subject'] = Header(mailsubject.encode('ISO-2022-JP'), 'ISO-2022-JP') try: p = os.popen("%s -t -i -f %s" % ( sendmailpath, mailfrom ), "w") p.write( msg.as_string() ) status = p.close() except: pass return status ######################################################################## if __name__ == '__main__': mailto = 'hoge@hoge.com' mailcc = 'hage@hage.com' mailbcc = 'hage@hage.com' mailfrom= 'hage@from.com' mailsubject = u'メールテスト' # unicode mailbody = u''' \ sendmailjpを使って送りました. '''# unicode print sendmailjp(mailto, mailcc, mailbcc, mailfrom, mailsubject, mailbody ) |