Advertisement
Guest User

Untitled

a guest
Jul 19th, 2017
501
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.65 KB | None | 0 0
  1. import os
  2. import smtplib
  3. from email.mime.multipart import MIMEMultipart
  4. from email.mime.base import MIMEBase
  5. from email.mime.text import MIMEText
  6. from email import encoders
  7.  
  8.  
  9. def send_email(message, subject, toaddrs, attach_file):
  10.  
  11. fromaddr = 'myemmail@gmail.com'
  12. username = fromaddr
  13. password = 'password'
  14.  
  15. msg = MIMEMultipart()
  16. msg['From'] = fromaddr
  17. msg['To'] = toaddrs
  18. msg['Subject'] = subject
  19. body = message
  20. msg.attach(MIMEText(body, 'html'))
  21. if attach_file is not False:
  22. for file in attach_file:
  23. with open(file, 'rb') as fp:
  24. process = MIMEBase('application', 'octet-stream')
  25. process.set_payload(fp.read())
  26. encoders.encode_base64(process)
  27. process.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))
  28. msg.attach(process)
  29.  
  30. server = smtplib.SMTP('smtp.gmail.com', 587)
  31. server.starttls()
  32. server.login(username, password)
  33. text = msg.as_string()
  34. server.sendmail(fromaddr, [toaddrs], text)
  35. server.quit()
  36.  
  37.  
  38. def get_attach_num():
  39. while True:
  40. try:
  41. ask = int(input('Number of attachments >>> '))
  42. return ask
  43. except ValueError:
  44. print('Wrong value entered')
  45.  
  46.  
  47. def yes_no_attach():
  48. while True:
  49. try:
  50. ask_attach = input('Any attachments?nY/N? >>> ').lower()
  51. if ask_attach == 'y':
  52. attach_num = get_attach_num()
  53. return attach_num
  54. elif ask_attach == 'n':
  55. return ask_attach
  56. except ValueError:
  57. print('Wrong value entered')
  58.  
  59.  
  60. def main():
  61. attach = []
  62. subject = input('Subject >>> ')
  63. toaddrs = input('Address of the recipient >>> ')
  64. message = input('Your message >>> ')
  65. ask_attach = yes_no_attach()
  66. if ask_attach == 'n':
  67. try:
  68. send_email(str(message), str(subject), str(toaddrs), attach_file=False)
  69. print('Email has been sent')
  70. except smtplib.SMTPRecipientsRefused:
  71. print('No recipient(s) selected')
  72. print('Try again')
  73. main()
  74. else:
  75. ask = ask_attach
  76. for times in range(ask):
  77. attach.append(input('Path to the file %s that you with to attach >>> ' % str(times + 1)))
  78. try:
  79. send_email(str(message), str(subject), str(toaddrs), attach)
  80. print('Email has been sent')
  81. except (FileNotFoundError, smtplib.SMTPRecipientsRefused):
  82. print('No attachment(s)\recipient(s) selected')
  83. print('Try again')
  84. main()
  85.  
  86.  
  87. if __name__ == '__main__':
  88. print('Welcome to SendGmail V2 by AJ')
  89. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement