python + smtp如何发送带附件的电子邮件?

时间:2017-04-18 03:52:19

标签: python

我正在尝试使用smpt发送带有attachmant的电子邮件。但是,我的文件是“doc”或“txt”类型,我想以“pdf”类型发送附件。是否有未知的param可以执行此操作?

import smtplib
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import os
server=smtplib.SMTP()
server.connect("smtp..com")
server.login("TTTTT@163.com","YYYYYY")
msg=MIMEMultipart('')
msg['From']="TTTTT@163.com"
msg['Subject']="opp"
with open("D:\log1.doc", 'rb') as f:
   content = base64.standard_b64encode(f.read()).decode()
part = MIMEApplication(content)
newfilename = 'resume.pdf'
part.add_header('Content-Disposition', 'attachment', filename=newfilename)
msg.attach(part)
msg['To']="XXX@gmail.com"
server.send_message(msg)

使用代码,错误发生!附件无法打开!我怎么解决这个问题? 谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

您无法获取.txt文件并以.pdf形式通过电子邮件发送。您需要先将其转换为PDF。您可以尝试重命名文件,从.txt到.pdf,但这样做不会很多,因为您需要设置内容处置和内容类型。

https://www.davidfischer.name/2015/08/generating-pdfs-with-and-without-python/ How to create a PDF with python

答案 1 :(得分:0)

import string
import time
from email.header    import Header
from email.mime.text import MIMEText
from getpass         import getpass
from smtplib         import SMTP_SSL
from email.MIMEMultipart import MIMEMultipart 

import smtplib 
msg = MIMEMultipart()
filename = "textfile.txt"
f = file(filename)
fromaddr = '*******@gmail.com'
toaddrs  = 'gamil addr'
#msg = 'There was a terrible error that occured and I wanted you to know!'

attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment',   filename=filename)           
msg.attach(attachment)
# Credentials (if needed)
username = 'gamil addr'
password = 'passwrd'

# The actual mail send
#server = smtplib.SMTP('smtp.gmail.com:587')
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg.as_string() )
server.quit()