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
https://support.google.com/accounts/answer/185833?hl=en
## eysackwdogjanekv
import smtplib
mail_server = smtplib.SMTP('smtp.gmail.com',587)
mail_server.ehlo()
mail_server.starttls()
password = input('Please provide your password:')
import getpass
email = getpass.getpass('Please provide the email:')
password = getpass.getpass('Please provide the password:')
mail_server.login(email,password)
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()
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:')
mail_server.login(email,password)
mail_server.list()
mail_server.select('INBOX')
typ, data = mail_server.search(None, 'SUBJECT Test-Python')
typ
data
email_id = data[0]
email_id
result, email_data = mail_server.fetch(email_id, '(RFC822)')
## email_data
result
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
for part in email_message.walk():
if part.get_content_type() == 'text/plain':
body = part.get_payload(decode = True)
print(body)