Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

imaplib

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 :).

like image 843
vernomcrp Avatar asked Sep 22 '10 13:09

vernomcrp


People also ask

How do you email in Python?

Use Python's built-in smtplib library to send basic emails. Send emails with HTML content and attachments using the email package. Send multiple personalized emails using a CSV file with contact data. Use the Yagmail package to send email through your Gmail account using only a few lines of code.

What is IMAP Python?

Python's client side library called imaplib is used for accessing emails over imap protocol. IMAP stands for Internet Mail Access Protocol. It was first proposed in 1986. Key Points: IMAP allows the client program to manipulate the e-mail message on the server without downloading them on the local computer.

What is IMAP account?

IMAP (Internet Messaging Access Protocol) With IMAP accounts, messages are stored in a remote server. Users can log in via multiple email clients on computers or mobile device and read the same messages.


2 Answers

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.

like image 173
Muhammad Alkarouri Avatar answered Oct 24 '22 00:10

Muhammad Alkarouri


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

import imaplib
from email.message import Message
from time import time

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

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

connection.append('INBOX', '', imaplib.Time2Internaldate(time()), str(new_message).encode('utf-8'))
  • The official imaplib documentation.
  • More detailed examples of using imaplib.
like image 20
Chris McCormick Avatar answered Oct 24 '22 00:10

Chris McCormick