Advertisement
gruntfutuk

send email attachments

Jul 8th, 2019
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | None | 0 0
  1. from random import randint
  2. from pathlib import Path
  3. import smtplib
  4. from email.mime.text import MIMEText
  5. from email.mime.multipart import MIMEMultipart
  6. from email.mime.base import MIMEBase
  7. from email import encoders
  8. import os.path
  9.  
  10. email_server_credentials = r'../.ssh/email_server_credentials.csv'  # keeping a secret
  11.  
  12. def send_email(send_to_email, file_location, subject):  
  13.     # Setup headers
  14.     message = subject
  15.     msg = MIMEMultipart()
  16.     msg['From'] = email
  17.     msg['To'] = send_to_email
  18.     msg['Subject'] = subject
  19.     msg.attach(MIMEText(message, 'plain'))
  20.  
  21.     # Setup the attachment
  22.     filename = os.path.basename(file_location)
  23.     attachment = open(file_location, "rb")
  24.     part = MIMEBase('application', 'octet-stream')
  25.     part.set_payload(attachment.read())
  26.     encoders.encode_base64(part)
  27.     part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
  28.  
  29.     # Attach the attachment to the MIMEMultipart object
  30.     msg.attach(part)
  31.     server = smtplib.SMTP(smtpserver, 587)
  32.     server.starttls()
  33.     server.login(email, password)
  34.     text = msg.as_string()
  35.     server.sendmail(email, send_to_email, text)
  36.     server.quit()
  37.  
  38. # get my email server credentials
  39. with open(email_server_credentials) as f:
  40.         smtpserver, email, password, email_prefix, email_domain = f.read().split(',')
  41.        
  42. number_of_ids = 3
  43. ids = []
  44.  
  45. # generate list of random numbers
  46. while len(ids) < number_of_ids:
  47.     id = randint(1000, 1999)
  48.     if not id in ids:
  49.         ids.append(id)
  50.        
  51. # create files
  52. for id in ids:
  53.     Path(f'{id}.pdf').touch()
  54.  
  55. # send messages
  56. for id in ids:
  57.     if os.path.isfile(f'{id}.pdf'):
  58.         send_email(f'{email_prefix}{id}{email_domain}', f'{id}.pdf', f'pdf for {id}')
  59.         print(f'Sent email for id {id}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement