Python透過Gamil寄送Email並且附加檔案
如果執行中出現
"smtplib.SMTPAuthenticationError: (535, '5.7.8 Username and Password not accepted. Learn more at\n5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 g66sm2224117qgf.37 - gsmtp') http://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python/27515833#27515833"
錯誤,代表有權限的問題。
可以去Google的說明連結或是直接這邊調整權限
要調整成
低安全性應用程式
[PS如果有用兩階段認證,電話的就好像還找不到解決方式,建議另外建立個MAIL來寄送]
範例Code
#!/usr/bin/env python
# encoding: utf-8
import os
import sys
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
COMMASPACE = ', '
def main():
sender = '你的EMAIL'
gmail_password = '你的EMAIL密碼'
recipients = ['收件人01的EMAIL','收件人02的EMAIL']
# 建立郵件主題
outer = MIMEMultipart()
outer['Subject'] = '主題'
outer['To'] = COMMASPACE.join(recipients)
outer['From'] = sender
outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
# 檔案位置 在windows底下記得要加上r 如下 要完整的路徑
attachments = [r'C:\Users\witkaiy\OneDrive\code sample\work\your_file.xls']
# 加入檔案到MAIL底下
for file in attachments:
try:
with open(file, 'rb') as fp:
print ('can read faile')
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()
# 寄送EMAIL
try:
with smtplib.SMTP('smtp.gmail.com', 587) as s:
s.ehlo()
s.starttls()
s.ehlo()
s.login(sender, gmail_password)
s.sendmail(sender, recipients, composed)
s.close()
print("Email sent!")
except:
print("Unable to send the email. Error: ", sys.exc_info()[0])
raise
if __name__ == '__main__':
main()
目前測試是可以寄送MAIL沒有問題