Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

pythonでメール送る その2:Gmail経由画像付き_危険編

前回の記事では、本文だけの簡単なメール送信を扱いました。
shuzo-kino.hateblo.jp

今度はMIME形式をつかって画像を添付して送信する方法を考えます。

実際のところ

# smtplib module send mail
import sys
import os
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Gmail Sign In
gmail_sender = 'mail@yours.com'
gmail_passwd = 'XXXX'

SUBJECT = 'TEST'
TO = 'target@yours.com'
FROM = gmail_sender

outer = MIMEMultipart()
outer['Subject'] = SUBJECT
outer['To'] = TO
outer['From'] = FROM
outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

part1 = MIMEText("マルセイバターサンド", 'plain')
outer.attach(part1)

# Add attachments.
attachments = ['/Users/shuzo_kino/imgtest/img.jpg']

# attachments to base64 data. 
for file in attachments:
  try:
    with open(file, 'rb') as fp:
      msg = MIMEBase('application', "octet-stream")          
      msg.set_payload(fp.read())
    encoders.encode_base64(msg)      
    msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))
    outer.attach(msg)
  except:
    print("Unable to open one of the attachments. Error: ", sys.exc_info()[0])           
    raise

composed = outer.as_string()

try:
  with smtplib.SMTP('smtp.gmail.com', 587) as s:
    s.ehlo()
    s.starttls()
    s.login(gmail_sender, gmail_passwd)
    s.sendmail(gmail_sender, TO, composed)
    s.close()
  print("Email sent!")
except:
  print ('error sending mail')
  raise

画像はこちらからお借りしました。
マルセイバターサンド - Wikipedia

結果はこんな感じ。
f:id:shuzo_kino:20160728200639p:plain