2016-06-16 18 views
0

私は、添付ファイル付きの電子メールを送信するためのPython(v3.4)スクリプトを作成するためにステップバイステップで試しています。私はすでにsmtplibライブラリを使用して添付ファイルなしで1つを正常に送信します。しかし、添付ファイルを追加するには、MIMEMultipartオブジェクトを作成する必要があるようです。ここまで奇妙なことはありません。私はSMTPException除いて、このPython sendemail()MIMEMultipartが動作しない

import smtplib 
from email.mime.multipart import MIMEMultipart 

try: 
fromaddr = '[email protected]' 
toaddrs = ['[email protected]'] 

# Create the container (outer) email message. 
msg = MIMEMultipart() 
msg['Subject'] = 'Our family reunion' 
# me == the sender's email address 
# family = the list of all recipients' email addresses 
msg['From'] = fromaddr 
msg['To'] = toaddrs 
msg.preamble = 'Our family reunion' 




password = 'ExamplePassword88' 

# The actual mail send 
server = smtplib.SMTP('smtp.gmail.com:587') 
server.starttls() 
server.ehlo() 
server.login(fromaddr,password) 


text = msg.as_string() 
server.sendmail(fromaddr, toaddrs, text) 
print("Successfully sent email") 

を作成した例に基づいて

: プリント( "エラー:メールを送信することができません") ついに: server.quit()

しかしライン" text = msg.as_string() "次のエラーが表示されます

Traceback (most recent call last): File "C:/Users/user/upload_file.py", line 37, in text = msg.as_string() File "C:\Python34\lib\email\message.py", line 159, in as_string g.flatten(self, unixfrom=unixfrom) File "C:\Python34\lib\email\generator.py", line 112, in flatten self._write(msg) File "C:\Python34\lib\email\generator.py", line 192, in _write self._write_headers(msg) File "C:\Python34\lib\email\generator.py", line 219, in _write_headers self.write(self.policy.fold(h, v)) File "C:\Python34\lib\email_policybase.py", line 314, in fold return self._fold(name, value, sanitize=True) File "C:\Python34\lib\email_policybase.py", line 352, in _fold parts.append(h.encode(linesep=self.linesep, AttributeError: 'list' object has no attribute 'encode'

私は何ができますか?

答えて

0

問題は、変数toaddrsがリストであることです。

アドレスのリストは、アドレスがカンマで区切られた文字列である必要があります。

msg['To'] = ",".join(toaddrs) 

その後すべて正常に動作するはずです。 詳細はこちらをご覧ください。 How to send email to multiple recipients using python smtplib?

関連する問題