本文利用 Python 實作 Gmail SMTP 寄信程式,可以指定複數個收信者以及附檔。

#!/usr/bin/env python

# USAGE: ./sendgmail.py path_to_filename [assigned_attachment_name]
# if not assign assigned_attachment_name, the attachment is named as original path_to_filename

from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from smtplib import SMTP
import smtplib
import sys

sender = '{YOUR_ID}@gmail.com'
passwd = '{YOUR_PASSWD}'
receivers = ['{RECEIVER_1}@gmail.com','{RECEIVER_2}@gmail.com']

emails = [elem.strip().split(',') for elem in receivers]
msg = MIMEMultipart()
msg['Subject'] = "{YOUR_MAIL_SUBJECT}"
msg['From'] = sender
msg['To'] = ','.join(receivers)

msg.preamble = 'Multipart massage.\n'
part = MIMEText("{YOUR_MAIL_CONTENT}")
msg.attach(part)

part = MIMEApplication(open(str(sys.argv[1]),"rb").read())
if len(sys.argv) > 2:
    attachname = str(sys.argv[2])
else:
    attachname = str(sys.argv[1])

part.add_header('Content-Disposition', 'attachment', filename=attachname)
msg.attach(part)

smtp = smtplib.SMTP("smtp.gmail.com:587")
smtp.ehlo()
smtp.starttls()
smtp.login(sender, passwd)

smtp.sendmail(msg['From'], emails , msg.as_string())
print 'Send mails to',msg['To']

執行之後會跳出錯誤並要求用瀏覽器登入

File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 622, in login
raise SMTPAuthenticationError(code, resp)
    smtplib.SMTPAuthenticationError: (534, '5.7.14 >https://accounts.google.com/signin/continue?sarp=1
    &scc=1&plt=AKgnsbsB\n5.7.14 NybLGH37NNlC7xFxN-8jgqZPMhvzcWIHE8FpSbdMPc6rVhdA3NKpB381zkebEsZYb39-j7\n
    5.7.14 Q8oKCT8WKWEX8_ridGsmunFxOuvdu6W8zzANykKnk3NyN4p7ONGx0RloSBVtUdY24W8c67\n5.7.14 ctLEzwXqUgyKdhkadSs15az5cU7W
    m7_GgLWKVy4CSnuhl-kcuM8jq6jIbNn0OiBwrUACj9\n5.7.14 GYE5DrUUnGzyqQlxufpOfVQ13v7NM> 
    Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/
    78754 s84sm17035953pfg.128 - gsmtp')

此時不用緊張,訪問 https://accounts.google.com 並登入自己的google帳號
選擇 Connected apps & sites

google_sendmail_1

 

接下來打開 Allow less secure apps,再執行一次script就可以登入SMTP並且成功寄信!

 

google_sendmail_2

 

Facebook Comments