简体   繁体   English

Imaplib从带有附件的Gmail转发邮件(Python)

[英]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. 我需要从gmail获取邮件(此邮件可以包含附件),然后从另一封电子邮件转发此邮件。 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() ? 另外,如果您使用的是Python 3.2+,是否尝试过使用smtp.send_message(message, FROM_ADDR, TO_ADDR)而不是smtp.sendmail() It looks like it tries hard to do things more correctly, especially regarding character encoding in the SMTP connection. 看起来它努力尝试更正确地做事,尤其是在SMTP连接中的字符编码方面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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