使用Python 2.7(smtplib)发送电子邮件附件(.txt文件) [英] Sending Email attachment (.txt file) using Python 2.7 (smtplib)

查看:488
本文介绍了使用Python 2.7(smtplib)发送电子邮件附件(.txt文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图发送一个.txt文件作为附件,我找不到正确的代码工作。这是我的代码:

So I'm trying to send a .txt file as an attachment and I can't find the right code to work. Here is my code:

import pythoncom
import win32gui
import win32console
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


fromaddr = 'zover1@gmail.com'
toaddrs = 'zover2@gmail.com'
msg = "contrl text file"
username = 'zover1@gmail.com'
password= 'xxxxxxxxxxxx'
server = smtplib.SMTP('smtp.gmail.com:587')
f = file("d:/control.txt")
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename="d:/control.txt")
msg.attach(attachment)
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

当我运行模块时,我收到这个错误:

And when I run the module I get this error:

Traceback (most recent call last):
  File "C:\Python278\emailonlytester.pyw", line 19, in <module>
msg.attach(attachment)
AttributeError: 'str' object has no attribute 'attach'

任何帮助将不胜感激。

推荐答案

您可以尝试使用python发送附件文件: / p>

You can try this to send an attached file with python:

msg = MIMEMultipart()
msg['From'] = 'your adress'
msg['To'] = 'someone'
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = 'a random subject'
msg.attach(MIMEText("some text"))
file = 'd:/control.txt'
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(open(file,'rb').read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
msg.attach(attachment)

这是创建的一部分电子邮件,而不是发送。

This is the part for the creation of the Email, not the sending.

这篇关于使用Python 2.7(smtplib)发送电子邮件附件(.txt文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆