mail.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. """
  2. 程式用途
  3. AI主播寄送郵件。
  4. 參考
  5. Gmail SMTP: https://kb.synology.com/zh-tw/SRM/tutorial/How_to_use_Gmail_SMTP_server_to_send_emails_for_SRM
  6. """
  7. import dataset
  8. import smtplib
  9. from email.mime.multipart import MIMEMultipart # email內容載體
  10. from email.mime.text import MIMEText # 用於製作文字內文
  11. from email.mime.base import MIMEBase # 用於承載附檔
  12. from email import encoders # 用於附檔編碼
  13. import datetime
  14. import ssl
  15. def get_db(db_name, table_name):
  16. db = dataset.connect(f'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/{db_name}?charset=utf8mb4')
  17. user_table = db[table_name]
  18. return user_table
  19. def mail_to_users(user_id: int, subject: str, contents: str):
  20. """
  21. 1. 透過id查詢DB, 找出使用者email、username
  22. 2. 訊息制定(如: Aaron, 您的影片於2021/7/12 14:00 "ChoozMo測試影片" 完成了,請前往官網: "url")下載。
  23. 3. 傳送。
  24. - 根據server不同,可以區分。
  25. - 先用Gmail。(可以動就好)
  26. """
  27. # 連線DB得到使用者郵件、姓名
  28. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  29. rows = db.query(f'SELECT * FROM users WHERE id={user_id}')
  30. for row in rows:
  31. email = row['email']
  32. name = row['username']
  33. print(name, email)
  34. # 寄件者使用的Gmail帳戶資訊
  35. time_now = datetime.datetime.utcnow() + datetime.timedelta(hours=8)
  36. with open('password.txt') as f:
  37. gmail_user, gmail_password = f.readlines()
  38. # gmail_user = 'aaron@choozmo.com'
  39. # gmail_password = 'Choozmo1015'
  40. from_address = gmail_user
  41. # 設定信件內容與收件人資訊
  42. to_address = email if type(email) == type([]) else [email]
  43. # 開始組合信件內容
  44. mail = MIMEMultipart()
  45. mail['From'] = from_address
  46. mail['To'] = ', '.join(to_address)
  47. mail['Subject'] = subject
  48. # 將信件內文加到email中
  49. mail.attach(MIMEText(contents))
  50. print(to_address)
  51. # 設定smtp伺服器並寄發信件
  52. smtpserver = smtplib.SMTP_SSL("smtp.gmail.com", 465)
  53. smtpserver.ehlo()
  54. smtpserver.login(gmail_user, gmail_password)
  55. smtpserver.sendmail(from_address, to_address, mail.as_string())
  56. smtpserver.quit()
  57. if __name__ == '__main__':
  58. mail_to_users(4, 'subject', 'contents')