chz_gmaillib.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import smtplib
  2. import traceback
  3. import os
  4. from email.mime.text import MIMEText
  5. from email.mime.image import MIMEImage
  6. from email.mime.multipart import MIMEMultipart
  7. from email.message import EmailMessage
  8. import codecs
  9. import jinja2
  10. # mailobj['toaddr']
  11. # mailobj['title']
  12. #'合作洽談 | ChoozMo '
  13. def mail_to_other(mailobj):
  14. gmail_user = 'jared@choozmo.com'
  15. gmail_password='jgferbhelzrtgsbb'
  16. sent_from = gmail_user
  17. toaddr=mailobj['toaddr']
  18. to = [toaddr]
  19. msg = MIMEMultipart()
  20. msg['Subject'] = mailobj['title']
  21. msg['From'] = 'jared@choozmo.com'
  22. msg['To'] = toaddr
  23. image_paths=['c:/tmp/images/image-1.png','c:/tmp/images/image-2.png','c:/tmp/images/image-3.png','c:/tmp/images/image-4.png','c:/tmp/images/image-5.png','c:/tmp/images/image-6.png','c:/tmp/images/image-7.jpeg','c:/tmp/images/image-8.jpeg']
  24. msgAlternative = MIMEMultipart('alternative')
  25. msg.attach(msgAlternative)
  26. #fr=codecs.open('c:/tmp/final.html','r','utf-8')
  27. fr=codecs.open('c:/tmp/index.html','r','utf-8')
  28. content=fr.read()
  29. fr.close()
  30. display=mailobj['display']
  31. # display={}
  32. # display['custname']='敬啟者'
  33. # display['client']='j22332'
  34. # display['email']=toaddr
  35. # display['campaign']='20220305-test'
  36. templateLoader = jinja2.FileSystemLoader(searchpath='c:/tmp')
  37. templateEnv = jinja2.Environment(loader=templateLoader)
  38. TEMPLATE_FILE = 'index.html'
  39. template = templateEnv.get_template(TEMPLATE_FILE)
  40. outputText = template.render(display=display)
  41. content=outputText
  42. text = MIMEText(content,'html','utf-8')
  43. counter = 1
  44. for fp in image_paths:
  45. fp = open(fp, 'rb')
  46. msgImage = MIMEImage(fp.read())
  47. fp.close()
  48. # Define the image's ID as referenced above
  49. msgImage.add_header('Content-ID', '<image'+str(counter)+'>')
  50. msgAlternative.attach(msgImage)
  51. counter += 1
  52. msgAlternative.attach(text)
  53. try:
  54. server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
  55. server.ehlo()
  56. server.login(gmail_user, gmail_password)
  57. server.sendmail(sent_from, to, msg.as_string())
  58. server.close()
  59. print ('Email sent!')
  60. except:
  61. traceback.print_exc()
  62. print ('Something went wrong...')