如何使用SMTP发送附件?

Jas*_*ker 21 python email smtp attachment smtplib

我想编写一个使用Python的smtplib发送电子邮件的程序.我搜索了文档和RFC,但找不到任何与附件相关的内容.因此,我确信我错过了一些更高级别的概念.有人能告诉我附件如何在SMTP中工作吗?

Kev*_*chs 29

以下是带有PDF附件,文本"正文"并通过Gmail发送的邮件示例.

# Import smtplib for the actual sending function
import smtplib

# For guessing MIME type
import mimetypes

# Import the email modules we'll need
import email
import email.mime.application

# Create a text/plain message
msg = email.mime.Multipart.MIMEMultipart()
msg['Subject'] = 'Greetings'
msg['From'] = 'xyz@gmail.com'
msg['To'] = 'abc@gmail.com'

# The main body is just another attachment
body = email.mime.Text.MIMEText("""Hello, how are you? I am fine.
This is a rather nice letter, don't you think?""")
msg.attach(body)

# PDF attachment
filename='simple-table.pdf'
fp=open(filename,'rb')
att = email.mime.application.MIMEApplication(fp.read(),_subtype="pdf")
fp.close()
att.add_header('Content-Disposition','attachment',filename=filename)
msg.attach(att)

# send via Gmail server
# NOTE: my ISP, Centurylink, seems to be automatically rewriting
# port 25 packets to be port 587 and it is trashing port 587 packets.
# So, I use the default port 25, but I authenticate. 
s = smtplib.SMTP('smtp.gmail.com')
s.starttls()
s.login('xyz@gmail.com','xyzpassword')
s.sendmail('xyz@gmail.com',['xyz@gmail.com'], msg.as_string())
s.quit()
Run Code Online (Sandbox Code Playgroud)

  • 这解决了我通过电子邮件发送excel文件的问题,这很棒,因为它让我不能使用os.system调用Ruby!谢谢凯文! (2认同)

Mar*_*ark 19

这是我从我们所做的工作应用程序中删除的一个例子.它会创建一个带有Excel附件的HTML电子邮件.

  import smtplib,email,email.encoders,email.mime.text,email.mime.base

  smtpserver = 'localhost'
  to = ['email@somewhere.com']
  fromAddr = 'automated@hi.com'
  subject = "my subject"

  # create html email
  html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" '
  html +='"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">'
  html +='<body style="font-size:12px;font-family:Verdana"><p>...</p>'
  html += "</body></html>"
  emailMsg = email.MIMEMultipart.MIMEMultipart('alternative')
  emailMsg['Subject'] = subject
  emailMsg['From'] = fromAddr
  emailMsg['To'] = ', '.join(to)
  emailMsg['Cc'] = ", ".join(cc)
  emailMsg.attach(email.mime.text.MIMEText(html,'html'))

  # now attach the file
  fileMsg = email.mime.base.MIMEBase('application','vnd.ms-excel')
  fileMsg.set_payload(file('exelFile.xls').read())
  email.encoders.encode_base64(fileMsg)
  fileMsg.add_header('Content-Disposition','attachment;filename=anExcelFile.xls')
  emailMsg.attach(fileMsg)

  # send email
  server = smtplib.SMTP(smtpserver)
  server.sendmail(fromAddr,to,emailMsg.as_string())
  server.quit()
Run Code Online (Sandbox Code Playgroud)

  • 多部分子类型应该是"混合"而不是"替代",否则您将无法在某些电子邮件客户端中看到附加文件. (6认同)

Jür*_*ard 11

您想要查看的是email模块.它允许您构建MIME兼容的消息,然后使用smtplib发送.