尝试在python中附加电子邮件附件时出现奇怪的错误

时间:2014-10-21 05:39:29

标签: python python-3.x smtplib

我正在尝试使用python发送电子邮件。当我试图附加附件时,我收到一个奇怪的错误。

当我尝试将数组值传递给attachment.add_header()函数时出现错误,但是当我将该值赋给变量并尝试传递该变量时,它会起作用!奇怪的是变量和数组值具有相同的值

Works(此代码完美运行)

attachmentfile = attachment[0] # assign the array value to a variable and it workd
attachment = self.guess_and_get_attachment_type(attachmentfile)
# Set the filename parameter
attachment.add_header('Content-Disposition', 'attachment', filename = attachmentfile)
message.attach(attachment)

不起作用(只需删除变量赋值,代码就会出错)

attachment = self.guess_and_get_attachment_type(attachment[0])
# Set the filename parameter 
attachment.add_header('Content-Disposition', 'attachment', filename = attachment[0]
message.attach(attachment)

追溯

 File "Email.py", line 224, in <module>
    main()
  File "Email.py", line 221, in main
    mail.send_email()
  File "Email.py", line 202, in send_email
    email = Email(self.from_address ,  self.to_address ,  self.subject ,   self.body ,self.email_server ,attachment)
  File "Email.py", line 47, in __init__
    self.attach_attachment()
  File "Email.py", line 62, in attach_attachment
    self.attachment.set_attachment_type(self.message)
  File "Email.py", line 134, in set_attachment_type
    attachment.add_header('Content-Disposition', 'attachment', filename = attachment[0])
  File "/usr/lib/python3.4/email/message.py", line 391, in __getitem__
    return self.get(name)
  File "/usr/lib/python3.4/email/message.py", line 468, in get
    name = name.lower()
AttributeError: 'int' object has no attribute 'lower'

2 个答案:

答案 0 :(得分:0)

这取自this link

import smtplib
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
assert type(send_to)==list
assert type(files)==list
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for f in files:
   part = MIMEBase('application', "octet-stream")
   part.set_payload( open(file,"rb").read() )
   Encoders.encode_base64(part)
   part.add_header('Content-Disposition', 'attachment; filename="%s"' %    os.path.basename(f))
   msg.attach(part)

  smtp = smtplib.SMTP(server)
  smtp.sendmail(send_from, send_to, msg.as_string())
  smtp.close()

答案 1 :(得分:0)

问题是由于您在致电attachment时重新分配self.guess_and_get_attachment_type()

在第一个示例中,attachmentfileattachment[0]的原始值,在第二个示例中,attachment[0]是函数调用的结果。