【问题标题】:Python: Trying to send attachments via email ~ string error?Python:试图通过电子邮件发送附件〜字符串错误?
【发布时间】:2017-10-07 21:52:18
【问题描述】:

我正在尝试使用 python 通过电子邮件发送附件,但出现此错误:

msg.attach(msgImage) AttributeError: 'str' 对象没有属性 'attach'

代码如下:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.mime.image import MIMEImage


def send_email():
    fromaddr = 'testevpsa1@gmail.com'
    toaddrs  = 'Toemail'
    global msg
    subject = 'RESPOSTA'
    message = 'Subject: %s\n\n%s' % (subject, msg)

    username = 'testevpsa1@gmail.com'
    password = 'xxxxxxxx'

    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(username,password)

    fp = open ('C:\Python27\Scripts\pares.txt', 'rb')
    msgImage = MIMEImage (fp.read(), _subtype='txt')
    fp.close()
    msg.attach(msgImage)

    server.sendmail(fromaddr, toaddrs, message,  msg.as_string())
    server.quit()

msg = 'Email test, please, see the attachments'
send_email()

谁有什么问题的提示?

【问题讨论】:

  • 提示:msg 的类型是什么?
  • msg 是一个字符串,但我还是不明白这个问题,当脚本读取txt文件时,它不能将内容“附加”为字符串吗?

标签: python python-2.7 mime smtplib


【解决方案1】:

您的代码很奇怪且不正确。您开始使用高级概念,但没有语言、smtp 协议和电子邮件模块的基本知识。

您代码中的msg 变量具有str 类型。 str 是一个纯字符串 - 一个字符列表。它没有方法.attach

我猜你想使用 email.message 类的实例而不是字符串。此外,不需要使用全局变量。全局变量不好,在你的情况下完全没有必要使用全局变量。

【讨论】:

  • 感谢您的回答,我正在使用全局变量,因为将来它可能会在另一个函数中使用。
  • 如果你想写一个函数,稍后被另一个函数使用,那么全局变量是最差可能的参数传递方式。您需要使用普通函数参数,而不是全局变量。例如:def send_mail(msg):
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-30
相关资源
最近更新 更多