Reputation: 347
I am out of ideas how to solve this. I checked most smtplib threads and those about " AttributeError: 'tuple' object has no attribute 'encode'"
I am trying to create message template to send emails from Python3 script. For some reason, when I added message template I cannot fix that in any way.
import smtplib
import additional
import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
#server commends
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
#credentials of sender
FROM = "xxx.gmail.com"
PASSWORD = additional.x #hidden password in other .py file
#logging in
server.login(FROM, PASSWORD)
#template for recievers
TOADDR = ["reciever email"]
CC = ["FIRST CC", "2ND CC"]
SUBJECT = "testing"
TEXT = "Let's check if this works and I joined everything correctly"
#MSG template
FINAL_TO = CC + [TOADDR]
message = MIMEMultipart()
message['From'] = "Michal", FROM
message['To'] = TOADDR
message['Cc'] = ", ".join(CC)
message['Subject'] = SUBJECT
message.attach(MIMEText(TEXT))
MSG = message.as_string()
#Join reciever with CC
FINAL_TO = CC + [TOADDR]
server.sendmail(FROM, FINAL_TO, MSG)
TIME = datetime.datetime.now()
print("Email sent at {}".format(TIME))
As mentioned above, my output is :
Traceback (most recent call last):
File "/home/galander/Desktop/sending email/app.py", line 39, in <module>
MSG = message.as_string()
File "/usr/lib/python3.6/email/message.py", line 158, in as_string
g.flatten(self, unixfrom=unixfrom)
File "/usr/lib/python3.6/email/generator.py", line 116, in flatten
self._write(msg)
File "/usr/lib/python3.6/email/generator.py", line 195, in _write
self._write_headers(msg)
File "/usr/lib/python3.6/email/generator.py", line 222, in _write_headers
self.write(self.policy.fold(h, v))
File "/usr/lib/python3.6/email/_policybase.py", line 326, in fold
return self._fold(name, value, sanitize=True)
File "/usr/lib/python3.6/email/_policybase.py", line 369, in _fold
parts.append(h.encode(linesep=self.linesep, maxlinelen=maxlinelen))
AttributeError: 'tuple' object has no attribute 'encode'
Upvotes: 4
Views: 8614
Reputation: 1122382
Headers on a mime message must be strings. You have assigned a tuple to From
, and a list to To
.
Make those strings too:
message['From'] = "Michal <{}>".format(FROM)
message['To'] = ', '.join(TOADDR)
Upvotes: 11