以下是我的代码。它无法在解析级别的某处发送邮件。无法理解实际问题。操作系统是AWS提供的Ubuntu 14.04服务器。它必须发送带有两个附件的电子邮件。
import smtplib
import sys
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
fromaddr = "user@comany.com"
toaddr = str(sys.argv[1]).split(",")
ccaddr = str(sys.argv[2]).split(",")
bccaddr = str(sys.argv[3]).split(",")
subject = None
body = None
print sys.argv
with open("subject.txt") as f1:
subject = f1.read()
with open("body.txt") as f2:
body = f2.read()
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Cc'] = ccaddr
msg['Bcc'] = bccaddr
msg['Subject'] = subject.replace("DD",str(sys.argv[4])[6:2]).replace("MM",str(sys.argv[4])[4:2]).replace("YYYY",str(sys.argv[4])[0:4])
body = body.replace("DD",str(sys.argv[4])[6:2]).replace("MM",str(sys.argv[4])[4:2]).replace("YYYY",str(sys.argv[4])[0:4])
msg.attach(MIMEText(body, 'plain'))
for filename in str(sys.argv[5]).split(";"):
attachment = open(filename, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(fromaddr, "password")
server.sendmail(fromaddr, toaddr, msg.as_string())
server.quit()
这是错误:
File "send_mail.py", line 49, in <module>
server.sendmail(fromaddr, toaddr, msg.as_string())
File "/usr/lib/python2.7/email/message.py", line 137, in as_string
g.flatten(self, unixfrom=unixfrom)
File "/usr/lib/python2.7/email/generator.py", line 83, in flatten
self._write(msg)
File "/usr/lib/python2.7/email/generator.py", line 115, in _write
self._write_headers(msg)
File "/usr/lib/python2.7/email/generator.py", line 164, in _write_headers
v, maxlinelen=self._maxheaderlen, header_name=h).encode()
File "/usr/lib/python2.7/email/header.py", line 410, in encode
value = self._encode_chunks(newchunks, maxlinelen)
File "/usr/lib/python2.7/email/header.py", line 370, in _encode_chunks
_max_append(chunks, s, maxlinelen, extra)
File "/usr/lib/python2.7/email/quoprimime.py", line 97, in _max_append
L.append(s.lstrip())
AttributeError: 'list' object has no attribute 'lstrip'
答案 0 :(得分:1)
使用yagmail尝试一下。免责声明:我是yagmail的开发者。
import yagmail
yag = yagmail.SMTP("user@comany.com", "password")
yag.send(toaddrs, subject, body, str(sys.argv[5]).split(";"), ccaddrs, bccaddrs)
# ^ to ^subject ^ body ^ attachments ^ cc ^ bcc
它几乎是“做我想要的”,你可以提供字符串列表或单个字符串,甚至省略任何参数,这将是明智的。另一件很酷的事情是这里的附件是一个字符串列表;其中每个都将尝试作为文件加载(具有正确的mimetype)。
使用pip install yagmail
安装
答案 1 :(得分:0)
当我尝试将列表输入到msg ['To']时,我遇到了同样的问题。我将列表更改为字符串,我摆脱了问题。 ['test@my.com','another@my.com'] =&gt; 'test@my.com,another @ my.com'