import imaplib
import email
from email import message
import time


username = 'gmail_id'
password = '<PASSWORD>'

new_message = email.message.Message()
new_message.set_unixfrom('satheesh')
new_message['Subject'] = 'Sample Message'
# from gmail id
new_message['From'] = '<EMAIL>'
# to gmail id
new_message['To'] = '<EMAIL>'
# message data
new_message.set_payload('This is the body of the message.\n')
# print(new_message)
# you want to connect to a server; specify which server  and port
# server = imaplib.IMAP4('server', 'port')
server = imaplib.IMAP4_SSL('imap.googlemail.com')
# after connecting, tell the server who you are to login to gmail
# server.login('user', 'password')
server.login(username, password)
# this will show you a list of available folders
# possibly your Inbox is called INBOX, but check the list of mailboxes
response, mailboxes = server.list()
if response == 'OK':
    response, data = server.select("Inbox")
    response = server.append('INBOX', '', imaplib.Time2Internaldate(time.time()), str(new_message).encode('utf-8'))
    # print(response)
    if response[0] == 'OK':
       print("Gmail Appended Successfully")
    else:
        print("Not Appended")
        server.close()
    server.logout()

import imaplib
import email
from email import message
import time


username = 'gmail_id'
password = '<PASSWORD>'

new_message = email.message.Message()
new_message.set_unixfrom('satheesh')
new_message['Subject'] = 'Sample Message'
# from gmail id
new_message['From'] = '<EMAIL>'
# to gmail id
new_message['To'] = '<EMAIL>'
# message data
new_message.set_payload('This is the body of the message.\n')
# print(new_message)
# you want to connect to a server; specify which server  and port
# server = imaplib.IMAP4('server', 'port')
server = imaplib.IMAP4_SSL('imap.googlemail.com')
# after connecting, tell the server who you are to login to gmail
# server.login('user', 'password')
server.login(username, password)
# this will show you a list of available folders
# possibly your Inbox is called INBOX, but check the list of mailboxes
response, mailboxes = server.list()
if response == 'OK':
    response, data = server.select("Inbox")
    response = server.append('INBOX', '', imaplib.Time2Internaldate(time.time()), str(new_message).encode('utf-8'))
    # print(response)
    if response[0] == 'OK':
       print("Gmail Appended Successfully")
    else:
        print("Not Appended")
        server.close()
    server.logout()

# from gmail id # to gmail id # message data # print(new_message) # you want to connect to a server; specify which server  and port # server = imaplib.IMAP4('server', 'port') # after connecting, tell the server who you are to login to gmail # server.login('user', 'password') # this will show you a list of available folders # possibly your Inbox is called INBOX, but check the list of mailboxes # print(response)