codex

2011年11月12日土曜日

Python - メールの日本語対応化・・・(嬉)

先ほど失敗してエポケーしたはずだったが、しつこくpythonのメール関連のページを
見ていたら参考していたサイトに答えは載っていた・・・w
ウノウラボ by Zynga Japan: Pythonでメールを送信したい人のためのサンプル集

一番下のコメントにある、

msg = MIMEText(body, 'plain', encoding)

msg = MIMEText(body.encode(encoding), 'plain', encoding)
これで文字化けせずにメールが受信できた~(嬉)

とかいいながらウキウキと「馬鹿野郎~」とかつけて送信したらまたエラーw
なんだよ・・・と思って成功した時は「あいうえお、かきくけこ」だったので
「あいうえお、かきくけこ~」でテストしたら再現できた。「~」が犯人か。
いろいろ、調べると・・・むむ・・・エンコードの'ISO-2022-JP'ってシビアなのね。
PythonJISX0213 – アクセンスのおまけ

もう!・・・別に読めればいいんだから'ISO-2022-JP'の必要ないんじゃ・・・?
こりゃ、エンコードは'utf-8'でいいよね?

テストしたら「㌧㌦㍑~」も含めてエラーもなし。
#コードはuploadとかできないのか・・・

DOWNLOAD

sendmailAjp.py

# -*- coding: utf-8 -*-
import os
import glob
import codecs
import unicodedata
import mimetypes
from email import encoders
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.Header import Header

def attach_files(msg, attachements):
  for attachment in attachments:
    attachment = attachment.strip()
    for path in glob.glob(attachment):
      filename = os.path.basename(path)
      if not os.path.isfile(path):
        continue
      # Guess the content type based on the file's extension.  Encoding
      # will be ignored, although we should check for simple things like
      # gzip'd or compressed files.
      ctype, encoding = mimetypes.guess_type(path)
      if ctype is None or encoding is not None:
        # No guess could be made, or the file is encoded (compressed), so
        # use a generic bag-of-bits type.
        ctype = 'application/octet-stream'
      maintype, subtype = ctype.split('/', 1)
      if maintype == 'text':
        fp = open(path)
        # Note: we should handle calculating the charset
        part = MIMEText(fp.read(), _subtype=subtype)
        fp.close()
      elif maintype == 'image':
        fp = open(path, 'rb')
        part = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
      elif maintype == 'audio':
        fp = open(path, 'rb')
        part = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
      else:
        fp = open(path, 'rb')
        part = MIMEBase(maintype, subtype)
        part.set_payload(fp.read())
        fp.close()
        # Encode the payload using Base64
        encoders.encode_base64(part)
      # Set the filename parameter
      part.add_header('Content-Disposition', 'attachment', filename=filename)
      msg.attach(part)

def sendemail(email_name, email_user, email_pswd, mailto, subject, body, attachments, encoding):
  import smtplib

  # DON'T CHANGE THIS!
  # ...unless you're rewriting this script for your own SMTP server!
  smtp_server = 'smtp.gmail.com'
  smtp_port = 587

  # Build an SMTP compatible message
  msg = MIMEMultipart()
  msg['Subject'] = Header(subject, encoding)
  msg['To'] = mailto
  msg['From'] = email_name + " <" + email_user + ">"
  msg.attach(MIMEText(body.encode(encoding), 'plain', encoding))

  attach_files(msg, attachments)

  # Attempt to connect and send the email
  try:
    smtpObj = '' # Declare within this block.
    # Check for SMTP over SSL by port number and connect accordingly
    if( smtp_port == 465):
      smtpObj = smtplib.SMTP_SSL(smtp_server,smtp_port)
    else:
      smtpObj = smtplib.SMTP(smtp_server,smtp_port)
    smtpObj.ehlo()
    # StartTLS if using the default TLS port number
    if(smtp_port == 587):
      smtpObj.starttls()
      smtpObj.ehlo
    # Login, send and close the connection.
    smtpObj.login(email_user, email_pswd)
    smtpObj.sendmail(email_user, mailto, msg.as_string())
    smtpObj.close()
    return 1  # Return 1 to denote success!
  except Exception, err:
    # Print error and return 0 on failure.
    print err
    return 0

import sys
import android

if 'ascii'==sys.getdefaultencoding():
  stdin = sys.stdin
  stdout = sys.stdout
  reload(sys)
  sys.setdefaultencoding('utf-8')
  sys.stdin = stdin
  sys.stdout = stdout

droid = android.Android()

try:
  email_name = droid.getIntent().result[u'extras'][u'%EMAIL_NAME']
except:
  email_name = ''

try:
  email_user = droid.getIntent().result[u'extras'][u'%EMAIL_USER']
except:
  droid.makeToast('EMAIL_USER missing')
  sys.exit(1)

try:
  email_pswd = droid.getIntent().result[u'extras'][u'%EMAIL_PSWD']
except:
  droid.makeToast('EMAIL_PSWD missing')
  sys.exit(1)

try:
  mailto = droid.getIntent().result[u'extras'][u'%EMAIL_TO']
except:
  droid.makeToast('EMAIL_TO missing')
  sys.exit(1)

try:
  subject = droid.getIntent().result[u'extras'][u'%EMAIL_SUBJECT']
except:
  subject = ''

try:
  body = droid.getIntent().result[u'extras'][u'%EMAIL_BODY']
except:
  body = ''

try:
  attachments = droid.getIntent().result[u'extras'][u'%EMAIL_ATTACH']
  attachments = attachments.split(',')
except:
  attachments = ''

try:
  body = droid.getIntent().result[u'extras'][u'%EMAIL_ENCODING']
except:
  encoding = 'utf-8'

# Send email
if (sendemail(email_name, email_user, email_pswd, mailto, subject, body, attachments, encoding)):
  sys.exit(0)
else:
  # Exit with error if email is not sent successfully
  droid.makeToast('email failed')
  sys.exit(1)


0 件のコメント:

コメントを投稿