nesalexy
nesalexy

Reputation: 878

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)

Upvotes: 0

Views: 413

Answers (1)

Schnouki
Schnouki

Reputation: 7717

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.

Upvotes: 1

Related Questions