How to create an email and send it to specific mailbox with imaplib

落花浮王杯 提交于 2019-12-06 05:23:21

问题


I am trying to use python's imaplib to create an email and send it to a mailbox with specific name, e.g. INBOX. Anyone has some great suggestion :).


回答1:


The IMAP protocol is not designed to send emails. It is designed to manipulate mailboxes.

To create an email and send it you can use SMTP, as in smtplib.

To move an email that is already in a mailbox from one folder to another, you can copy the mail to the needed folder and delete it from the old one using uid, as in the answer here.




回答2:


You can use Python's built-in imaplib module and the append() command to append a mail message to an IMAP folder:

import imaplib

connection = imaplib.IMAP4_SSL(HOSTNAME)
connection.login(USERNAME, PASSWORD)

new_message = email.message.Message()
new_message["From"] = "hello@itsme.com"
new_message["Subject"] = "My new mail."
new_message.set_payload("This is my message.")

connection.append('INBOX', '', imaplib.Time2Internaldate(time.time()), str(new_message))
  • The official imaplib documentation.
  • More detailed examples of using imaplib.



回答3:


Since I cannot yet comment on user3556956's comment, here is the answer for python3 :

connection.append('INBOX', '', imaplib.Time2Internaldate(time.time()), str(new_message).encode('utf-8'))

In short you have to pass the message as a byte instead of a python string.




回答4:


No idea how they do it but doesn't Microsoft Outlook let you move an email from a local folder to a remote IMAP folder?



来源:https://stackoverflow.com/questions/3769701/how-to-create-an-email-and-send-it-to-specific-mailbox-with-imaplib

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!