简体   繁体   中英

Cannot forward an email with attachments using imap and smtplib

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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM