Skip to content

Instantly share code, notes, and snippets.

@jq2
Last active January 26, 2018 17:24
Show Gist options
  • Save jq2/88bcabddfdacd10ae9efc3ebada4d4be to your computer and use it in GitHub Desktop.
Save jq2/88bcabddfdacd10ae9efc3ebada4d4be to your computer and use it in GitHub Desktop.
SEND/RECEIVE E-mails, attach files(send files) through Python 3.6 (smtplib, imaplib, email, etc)
# last-updated: Fri Jan 26 15:24:25 -02 2018
def do_send_email(my_password, from_address, to_address, message_body, filepath_to_send, filename_to_send):
# sending a email
import smtp
from email.mime import multipart
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(my_email, my_password) # Você precisa logar com sua conta de email, insira sua senha!
msg = multipart.MIMEMultipart()
my_email = from_address
my_recipe = to_address
if not message_body:
msg_body = 'Open Your Mind && Follow The White Rabbit! @bitzer0'
else:
msg_body = message_body
msg['From'] = my_email
msg['To'] = my_recipe
msg['Subject'] = 'Use your fucking brain - Python is a powerful army'
msg.attach(MIMEText(msg_body, 'plain'))
filename = filename_to_send
attachment = open(filepath_to_send, 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename= %s' % filename)
msg.attach(part)
text = msg.as_string()
server.sendmail(my_email, my_recipe, text)
server.close
def do_read_all_emails(my_email, my_password):
# receiving/reading emails
import imaplib
import email
mail_server = imaplib.IMAP4_SSL('imap.gmail.com', 993)
mail_server.login(my_email, my_password)
mail_server.select('INBOX')
result, data = mail_server.uid('search', 'ALL')
mail_ids = data[0]
list_of_recp = mail_ids.split()
for tid in list_of_recp:
result, data = mail_server.fetch(tid, '(RFC822)')
if result == 'OK':
mail_data = email.message_from_bytes(data[0][1])
print('E_MAIL_DATA:%s' % str(mail_data))
mail_server.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment