使用smpt发送带有多个附件的电子邮件

时间:2020-05-25 22:37:14

标签: python python-3.x email smtp smtplib

我有这个脚本,可以将带有多个附件的电子邮件发送给多个用户。但是,附件的文件名被设置为其路径。

收到的文件

enter image description here

端子输出

enter image description here

谢谢,我如何将它们的名称设置为实际文件名。

“”“

import os 
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.MIMEBase import MIMEBase
from email import Encoders


#Set up crap for the attachments
files = "/tmp/test/dbfiles"
filenames = [os.path.join(files, f) for f in os.listdir(files)]
#print filenames


#Set up users for email
gmail_user = "joe@email.com"
gmail_pwd = "somepasswd"
recipients = ['recipient1','recipient2']

#Create Module
def mail(to, subject, text, attach):
   msg = MIMEMultipart()
   msg['From'] = gmail_user
   msg['To'] = ", ".join(recipients)
   msg['Subject'] = subject

   msg.attach(MIMEText(text))

   #get all the attachments
   for file in filenames:
      part = MIMEBase('application', 'octet-stream')
      part.set_payload(open(file, 'rb').read())
      Encoders.encode_base64(part)
      part.add_header('Content-Disposition', 'attachment; filename="%s"' % file)
      msg.attach(part)

   mailServer = smtplib.SMTP("smtp.gmail.com", 587)
   mailServer.ehlo()
   mailServer.starttls()
   mailServer.ehlo()
   mailServer.login(gmail_user, gmail_pwd)
   mailServer.sendmail(gmail_user, to, msg.as_string())
   # Should be mailServer.quit(), but that crashes...
   mailServer.close()

#send it
mail(recipients,
   "Todays report",
   "Test email",
   filenames)

“”“

2 个答案:

答案 0 :(得分:1)

此链接中可能有解决方案:

Python email MIME attachment filename

基本上,根据该帖子的解决方案是更改此行:

part.add_header('Content-Disposition', 'attachment; filename="%s"' % file)

此行:

part.add_header('Content-Disposition', 'attachment', filename=AFileName)

归结为最终更改:

  #get all the attachments
  for file in filenames:
  
  part = MIMEBase('application', 'octet-stream')
  part.set_payload(open(file, 'rb').read())
  Encoders.encode_base64(part)
  
  ***part.add_header('Content-Disposition', 'attachment', filename=file)***

  msg.attach(part)

Documentation on how to use add_header

希望有帮助! :D

更新

在for循环中使用它应为您提供文件名:

for file in filenames:

    actual_filenames = os.path.basename(file)

    #Your code

    part.add_header('Content-Disposition', 'attachment', filename=actual_filenames)

答案 1 :(得分:0)

如果在同一目录中:

import os                                  
for f in os.listdir('.'):                                                                                               
    fn, fext = os.path.splitext(f)