Guest User

Untitled

a guest
Nov 5th, 2018
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.76 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3.  
  4. import smtplib
  5. from email.mime.text import MIMEText
  6. from email.header import Header
  7. from email.mime.multipart import MIMEMultipart
  8. import mimetypes
  9. import sys
  10.  
  11. import argparse
  12. from argparse import ArgumentParser
  13.  
  14. parser = ArgumentParser(description="Mail X", add_help=True)
  15. parser.add_argument('-c', '--content', type=str,
  16. required=True, help=u"Mail content")
  17. parser.add_argument('-s', '--subject', type=str,
  18. required=True, help=u"Mail subject")
  19. parser.add_argument('-f', '--fromer', type=str,
  20. required=True, help=u"Mail sender")
  21. parser.add_argument('--files', nargs='*',
  22. help=u"Mail attachments,Support for multiple files")
  23. args = parser.parse_args()
  24.  
  25. # 第三方 SMTP 服务设置
  26. mail_host = ""
  27. mail_user = ""
  28. mail_pass = ""
  29.  
  30.  
  31. sender = ''
  32. receivers = [''] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
  33.  
  34. def sendmail(content, subject, source, files=None):
  35. """ sendmail """
  36. msg = MIMEMultipart('related')
  37. msg['From'] = Header(source, 'utf-8')
  38. msg['To'] = Header("伟大的安全工程师们", 'utf-8')
  39. # subject = 'Python SMTP 邮件测试'
  40. msg['Subject'] = Header(subject, 'utf-8')
  41. message = MIMEText(content, 'plain', 'utf-8')
  42. msg.attach(message)
  43.  
  44. if files:
  45. for file in files:
  46. ctype, encoding = mimetypes.guess_type(file)
  47. if ctype is None or encoding is not None:
  48. ctype = "application/octet-stream"
  49. maintype, subtype = ctype.split("/", 1)
  50. if maintype == "text":
  51. fp = open(file)
  52. # Note: we should handle calculating the charset
  53. attachment = MIMEText(fp.read(), _subtype=subtype)
  54. attachment.add_header(
  55. "Content-Disposition", "attachment", filename=file.split('/')[-1])
  56. fp.close()
  57. else:
  58. print("No Support File Type!")
  59. return 1
  60. msg.attach(attachment)
  61. try:
  62. smtpObj = smtplib.SMTP_SSL(mail_host, port=465)
  63. smtpObj.connect(mail_host) # 25 为 SMTP 端口号
  64. smtpObj.login(mail_user, mail_pass)
  65. smtpObj.sendmail(sender, receivers, msg.as_string())
  66. print "邮件发送成功"
  67. smtpObj.close()
  68. except smtplib.SMTPException:
  69. print "Error: 无法发送邮件"
  70.  
  71.  
  72. def main():
  73. # if len(sys.argv) == 4:
  74. # sendmail(sys.argv[1], sys.argv[2], sys.argv[3])
  75. # elif len(sys.argv) == 5:
  76. # sendmail(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
  77. # else:
  78. # print '请输入邮件内容,标题,发件人,附件'
  79. print(args)
  80. sendmail(args.content, args.subject, args.fromer, args.files)
  81.  
  82.  
  83. if __name__ == '__main__':
  84. main()
Add Comment
Please, Sign In to add comment