简体   繁体   中英

Imaplib forward mail from gmail with attachment (Python)

Sorry for my english. I need get mail from gmail(this mail can contains attachments) and forward this mail from another email. Bellow my code for forward mail:

            for email_id in reversed(items):
                status, data = self.imap.fetch(email_id, "(RFC822)")
                if status == 'OK':

                    if count == 2: // this message contains attachment
                        message = email.message_from_bytes(data[0][1])
                        message.replace_header("From", FROM_ADDR)
                        message.replace_header("To", TO_ADDR)

                        try:
                            smtp = smtplib.SMTP('smtp.gmail.com', 587)
                            smtp.starttls()
                            smtp.login(CLIENT_MAIL, CLIENT_PASSWORD)
                            smtp.sendmail(FROM_ADDR, TO_ADDR, message.as_string())
                            smtp.quit()
                            print("send mail")
                        except BaseException as e:
                            print(e)

                    count += 1

This code work if mail contains only text(without attachment)

What's your error message?

Also, if you're using Python 3.2+, have you tried using smtp.send_message(message, FROM_ADDR, TO_ADDR) instead of smtp.sendmail() ? It looks like it tries hard to do things more correctly, especially regarding character encoding in the SMTP connection.

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