0

I've read on how to forward an email using imaplib and stmplib. I grab these emails (have attachments) off of gmail, sort them and want to forward them to another email account.

My code is here, and looks very similar:

message.mail.replace_header("From", from_addresses)
message.mail.replace_header("To", to_addresses)
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(settings.RECEIPTS_EMAIL_ACCOUNT, settings.RECEIPTS_EMAIL_PASSWORD)
server.sendmail(from_addresses, to_addresses, message.mail.as_string())
server.close()

However, whenever it hits the sendmail line on message.mail.as_string(), the mail, then it crashes with

*** AttributeError: 'list' object has no attribute 'encode'

How can I convert this to something I can send through imaplib?

Community
  • 1
  • 1
Slamice
  • 693
  • 1
  • 9
  • 25

1 Answers1

0

According to its documentation, SMTP.sendmail() takes a single from address, not a list.

So, try:

server.sendmail(from_address, to_addresses, message.mail.as_string())

or

server.sendmail(from_addresses[0], to_addresses, message.mail.as_string())

Similarly, Message.replace_header should not be passed a list. Try this:

message.mail.replace_header("From", from_addresses[0])
message.mail.replace_header("To", to_addresses[0])
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(settings.RECEIPTS_EMAIL_ACCOUNT, settings.RECEIPTS_EMAIL_PASSWORD)
server.sendmail(from_addresses[0], to_addresses, message.mail.as_string())
server.close()
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Unfortunately it's break on `message.mail.as_string()` , from and to are both one address. I made that clearer in the question just now. – Slamice Jan 29 '16 at 22:28
  • In that case, the error is that you are passing a list to `replace_header()`. See my recent edit. – Robᵩ Jan 29 '16 at 22:38
  • You were totally right, thank you so much. I cant believe I didn't find that in debugging. – Slamice Jan 29 '16 at 23:26