2017年5月19日 星期五

[ Python 常見問題 ] How to send email attachments with Python

Source From Here 
Question 
I am having problems understanding how to email an attachment using Python. I have successfully emailed simple messages with the smtplib. Could someone please explain how to send an attachment in an email. I know there are other posts online but as a Python beginner I find them hard to understand. 

How-To 
Here's another, adapted from here
  1. import smtplib  
  2. from os.path import basename  
  3. from email.mime.application import MIMEApplication  
  4. from email.mime.multipart import MIMEMultipart  
  5. from email.mime.text import MIMEText  
  6. from email.utils import COMMASPACE, formatdate  
  7.   
  8.   
  9. def send_mail(send_from, send_to, subject, text, files=None,  
  10.               server="127.0.0.1"):  
  11.     assert isinstance(send_to, list)  
  12.   
  13.     msg = MIMEMultipart()  
  14.     msg['From'] = send_from  
  15.     msg['To'] = COMMASPACE.join(send_to)  
  16.     msg['Date'] = formatdate(localtime=True)  
  17.     msg['Subject'] = subject  
  18.   
  19.     msg.attach(MIMEText(text))  
  20.   
  21.     for f in files or []:  
  22.         with open(f, "rb") as fil:  
  23.             part = MIMEApplication(  
  24.                 fil.read(),  
  25.                 Name=basename(f)  
  26.             )  
  27.             part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)  
  28.             msg.attach(part)  
  29.   
  30.   
  31.     smtp = smtplib.SMTP(server)  
  32.     smtp.sendmail(send_from, send_to, msg.as_string())  
  33.     smtp.close()  

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...