Last active
July 14, 2020 02:03
-
-
Save mjdargen/a6f917602b503c6285807d71687b7964 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# get most recent gmail subject line | |
import sys | |
import imaplib | |
import email | |
import email.header | |
EMAIL_ACCOUNT = "[email protected]" | |
ACCOUNT_PW = "" | |
EMAIL_FOLDER = "INBOX" | |
SUBJECT = "" | |
# create IMAP object for gmail | |
M = imaplib.IMAP4_SSL('imap.gmail.com') | |
# attempt to login | |
try: | |
rv, data = M.login(EMAIL_ACCOUNT, ACCOUNT_PW) | |
except imaplib.IMAP4.error: | |
print("LOGIN FAILED!!! ") | |
sys.exit(1) | |
# select inbox | |
M.select(EMAIL_FOLDER) | |
print("Processing mailbox...\n") | |
# process inbox | |
rv, data = M.search(None, "ALL") | |
if rv != 'OK': | |
print("No messages found!") | |
sys.exit(1) | |
# get the most recent message | |
ids = data[0] # data is a list | |
id_list = ids.split() # ids is a space separated string | |
latest_email_id = id_list[-1] # get the latest id | |
# fetch the email body (RFC822) | |
result, data = M.fetch(latest_email_id, "(RFC822)") | |
if rv != 'OK': | |
print("ERROR getting message", latest_email_id) | |
sys.exit(1) | |
msg = email.message_from_bytes(data[0][1]) | |
hdr = email.header.make_header(email.header.decode_header(msg['Subject'])) | |
SUBJECT = str(hdr) | |
# print(f"Subject: {SUBJECT}") | |
# close and logout | |
M.close() | |
M.logout() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# sends email using gmail | |
# uses address: [email protected] | |
import smtplib | |
import ssl | |
# send_email arguments: | |
# recipient - str - recipient's email address | |
# subject - str - subject line of email | |
# body - str - body of email | |
def send_email(recipient, subject, body): | |
port = 465 # For SSL | |
smtp_server = "smtp.gmail.com" | |
EMAIL_ACCOUNT = "[email protected]" | |
ACCOUNT_PW = "" | |
msg = f"From: {EMAIL_ACCOUNT}\nTo: {recipient}\nSubject: {subject}\n\n{body}" | |
context = ssl.create_default_context() | |
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server: | |
server.ehlo() | |
server.login(EMAIL_ACCOUNT, ACCOUNT_PW) | |
server.sendmail(EMAIL_ACCOUNT, recipient, msg) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment