简体   繁体   中英

Show mail sent through SMTP server in my IMAP “Sent” mailbox

I am able to send a mail using a SMTP server:

self.smtp_connection.sendmail(
    'my_smtp_username@provider.com',
    recipients,  # list of To, Cc and Bcc mails
    mime_message.as_string()
)

But I can't see the mail sent in the "Sent" box in the 'my_smtp_username@provider.com' IMAP account. How can I make the mail be visible in this box?

The SMTP and IMAP protocols are two distincts things : mails sent through the SMTP server are not visible by the IMAP one.

Thus, you need to simulate this behaviour yourself, by sending the mail to your own address (but without adding you in the "To:" header of the MIME object) and then move the mail in the correct box:

Using an API abstraction, where smtp_connection and imap_connection are correctly initialized, with the same account, named 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()

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