Emails

Each major email provider has theit own SMTP(Simple mail Transfer protocol) server

Provider SMTP server domain name
Gmail smtp.gmail.com
Yahoo mail smtp.mail.yahoo.com

For Gmail users, we will need to generate an app password instead of normal password. This let's gmail know that the python script attempting to access the account is authorized by you.

Sending Emails

Generate App password for your gmail
https://support.google.com/accounts/answer/185833?hl=en

## eysackwdogjanekv
import smtplib
mail_server = smtplib.SMTP('smtp.gmail.com',587)
mail_server.ehlo()
(250,
 b'smtp.gmail.com at your service, [2601:246:5500:4340:de5:8b30:f503:796]\nSIZE 35882577\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8')
mail_server.starttls()
(220, b'2.0.0 Ready to start TLS')
password = input('Please provide your password:')
Please provide your password:hKjhi
import getpass
email = getpass.getpass('Please provide the email:')
Please provide the email:········
password = getpass.getpass('Please provide the password:')
Please provide the password:········
mail_server.login(email,password)
(235, b'2.7.0 Accepted')
from_address = email
to_address = 'sreebhavya.11@gmail.com'
subject = 'Hi-Python Script'
message = 'Test Script'
msg = 'Subject: '+subject+'\n'+message
mail_server.sendmail(from_address, to_address, msg)
{}
mail_server.quit()
(221, b'2.0.0 closing connection h11sm11029722ilh.69 - gsmtp')

Receiving mails

import imaplib
mail_server = imaplib.IMAP4_SSL('imap.gmail.com')
import getpass
email = getpass.getpass('Enter your email address:')
password = getpass.getpass('Enter your password:')
Enter your email address:········
Enter your password:········
mail_server.login(email,password)
('OK', [b'whoiskr@gmail.com authenticated (Success)'])
mail_server.list()
('OK',
 [b'(\\HasNoChildren) "/" "INBOX"',
  b'(\\HasNoChildren) "/" "Notes"',
  b'(\\HasChildren \\Noselect) "/" "[Gmail]"',
  b'(\\All \\HasNoChildren) "/" "[Gmail]/All Mail"',
  b'(\\Drafts \\HasNoChildren) "/" "[Gmail]/Drafts"',
  b'(\\HasNoChildren \\Important) "/" "[Gmail]/Important"',
  b'(\\HasNoChildren \\Sent) "/" "[Gmail]/Sent Mail"',
  b'(\\HasNoChildren \\Junk) "/" "[Gmail]/Spam"',
  b'(\\Flagged \\HasNoChildren) "/" "[Gmail]/Starred"',
  b'(\\HasNoChildren \\Trash) "/" "[Gmail]/Trash"'])
mail_server.select('INBOX')
('OK', [b'14006'])
typ, data = mail_server.search(None, 'SUBJECT Test-Python')
typ
'OK'
data
[b'14006']
email_id = data[0]
email_id
b'14006'
result, email_data = mail_server.fetch(email_id, '(RFC822)')
## email_data
result
'OK'
raw_email = email_data[0][1]
raw_email_string = raw_email.decode('utf-8')
import email
email_message = email.message_from_string(raw_email_string)
email_message
<email.message.Message at 0x7fa1387ee9d0>
for part in email_message.walk():

    if part.get_content_type() == 'text/plain':
        body = part.get_payload(decode = True)
        print(body)
b'Test Script\r\n'