Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:尝试通过电子邮件发送附件~字符串错误?_Python_Python 2.7_Mime_Smtplib - Fatal编程技术网

Python:尝试通过电子邮件发送附件~字符串错误?

Python:尝试通过电子邮件发送附件~字符串错误?,python,python-2.7,mime,smtplib,Python,Python 2.7,Mime,Smtplib,我正在尝试使用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()

我正在尝试使用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()

有人知道问题出在哪里吗?

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

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


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

提示:
msg
的类型是什么?
msg
是一个字符串,但我仍然不理解这个问题,当脚本读取txt文件时,它是否无法将内容作为字符串“附加”?谢谢您的回答,我之所以使用全局变量,是因为将来可能会在另一个函数中使用它。如果您想编写一个稍后将由另一个函数使用的函数,那么全局变量是传递参数的最糟糕方式。您需要使用普通函数参数,而不是全局变量。例如:
def send\u mail(msg):