使用SMTP从Python发送带附件的邮件

时间:2022-11-15 10:48:29

I HAVE A LITTLE PROBLEM.

我有一个小问题。

I USE:

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

msg = MIMEMultipart()
msg['From'] = 'me@gmail.com'
msg['To'] = 'you@gmail.com'
msg['Subject'] = 'simple email in python'
message = 'here is the email'
msg.attach(MIMEText(message))

mailserver = smtplib.SMTP('smtp.gmail.com',587)
# identify ourselves to smtp gmail client
mailserver.ehlo()
# secure our email with tls encryption
mailserver.starttls()
# re-identify ourselves as an encrypted connection
mailserver.ehlo()
mailserver.login('me@gmail.com', 'mypassword')

mailserver.sendmail('me@gmail.com','you@gmail.com',msg.as_string())

mailserver.quit()

AND EVERTHING IS OKAY - BUT I WOULD LIKE TO ADD A TXT FILE ATTACHMENT. CAN YOU HELP ME?

并且好了 - 但我想添加一个TXT文件附件。你能帮助我吗?

2 个解决方案

#1


0  

You could achieve it like this:

你可以这样做:

filename = ...
with open(filename,'r') as f:
    message = MIMEText(f.read())
    message.add_header('Content-Disposition', 'attachment', filename=filename)
    msg.attach(message)

where msg is the MIMEMultiPart object.

其中msg是MIMEMultiPart对象。

#2


0  

I FIND ANSWER TO BUT THANKS A LOT ! :)

我找到了感谢,但感谢很多! :)

 filename='/www/pages/DANE/komunikaty.txt'
    fp=open(filename,'rb')
    att = email.mime.application.MIMEApplication(fp.read(),_subtype="txt")
    fp.close()
    att.add_header('Content-Disposition','attachment',filename=filename)
    msg.attach(att)

#1


0  

You could achieve it like this:

你可以这样做:

filename = ...
with open(filename,'r') as f:
    message = MIMEText(f.read())
    message.add_header('Content-Disposition', 'attachment', filename=filename)
    msg.attach(message)

where msg is the MIMEMultiPart object.

其中msg是MIMEMultiPart对象。

#2


0  

I FIND ANSWER TO BUT THANKS A LOT ! :)

我找到了感谢,但感谢很多! :)

 filename='/www/pages/DANE/komunikaty.txt'
    fp=open(filename,'rb')
    att = email.mime.application.MIMEApplication(fp.read(),_subtype="txt")
    fp.close()
    att.add_header('Content-Disposition','attachment',filename=filename)
    msg.attach(att)