Casa > H > How To Send An Email With Attachments In Python

How to send an email with attachments in Python

  1. import smtplib 
  2. from email.mime.multipart import MIMEMultipart 
  3. from email.mime.text import MIMEText 
  4. from email.mime.base import MIMEBase 
  5. from email import encoders 
  6. mail_content = '''Hello, 
  7. This is a test mail. 
  8. In this mail we are sending some attachments. 
  9. The mail is sent using Python SMTP library. 
  10. Thank You 
  11. ''' 
  12. #The mail addresses and password 
  13. sender_address = '[email protected]
  14. sender_pass = 'xxxxxxxx' 
  15. receiver_address = '[email protected]
  16. #Setup the MIME 
  17. message = MIMEMultipart() 
  18. message['From'] = sender_address 
  19. message['To'] = receiver_address 
  20. message['Subject'] = 'A test mail sent by Python. It has an attachment.' 
  21. #The subject line 
  22. #The body and the attachments for the mail 
  23. message.attach(MIMEText(mail_content, 'plain')) 
  24. attach_file_name = 'TP_python_prev.pdf' 
  25. attach_file = open(attach_file_name, 'rb') # Open the file as binary mode 
  26. payload = MIMEBase('application', 'octate-stream') 
  27. payload.set_payload((attach_file).read()) 
  28. encoders.encode_base64(payload) #encode the attachment 
  29. #add payload header with filename 
  30. payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name) 
  31. message.attach(payload) 
  32. #Create SMTP session for sending the mail 
  33. session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port 
  34. session.starttls() #enable security 
  35. session.login(sender_address, sender_pass) #login with mail_id and password 
  36. text = message.as_string() 
  37. session.sendmail(sender_address, receiver_address, text) 
  38. session.quit() 
  39. print('Mail Sent') 

De Mert Terron

Como adormecer rápido à noite :: O que são algumas engenhocas de segurança que a maioria das pessoas deveria ter?