邮件显示“已发送”邮箱

问题描述:

我能够使用SMTP服务器发送邮件:邮件显示“已发送”邮箱

self.smtp_connection.sendmail(
    '[email protected]', 
    recipients, # list of To, Cc and Bcc mails 
    mime_message.as_string() 
) 

但我不能看到在“已发送”框发邮件在'[email protected]'IMAP帐户中。我怎样才能让邮件在这个盒子里可见?

SMTP和IMAP协议是两个区别东西:通过SMTP服务器发送的邮件不可见的IMAP之一。因此,您需要通过将邮件发送到您自己的地址(但没有将您添加到MIME对象的“To:”标题中),然后将邮件移动到正确的框中,从而自行模拟此行为:

利用API抽象,其中smtp_connectionimap_connection正确初始化,用相同的帐户,命名为self.email_account

def send(self, recipients, mime_message): 
    """ 
    From the MIME message (object from standard Python lib), we extract 
    information to know to who send the mail and then send it using the 
    SMTP server. 

    Recipients list must be passed, since it includes BCC recipients 
    that should not be included in mime_message header. 
    """ 
    self.smtp_connection.sendmail(
     self.email_account, 
     recipients + [self.email_account], 
     mime_message.as_string() 
    ) 

    ### On the IMAP connection, we need to move the mail in the "SENT" box 
    # you may need to be smarter there, since this name may change 
    sentbox_name = 'Sent' 

    # 1. Get the mail just sent in the INBOX 
    self.imap_connection.select_folder('INBOX', readonly=False) 
    sent_msg_id = self.imap_connection.search(['UNSEEN', 'FROM', self.username]) 
    if sent_msg_id: 
     # 2. Mark it as read, to not bother the user at each mail 
     self.imap_connection.set_flags(sent_msg_id, '\Seen') 
     # 3. Copy the mail in the sent box 
     self.imap_connection.copy(sent_msg_id, sentbox_name) 
     # 4. Mark the original to delete and clean the INBOX 
     self.imap_connection.set_flags(sent_msg_id, '\Deleted') 
     self.imap_connection.expunge()