Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # -*- coding: UTF-8 -*-
- import smtplib
- from email.mime.text import MIMEText
- from email.header import Header
- from email.mime.multipart import MIMEMultipart
- import mimetypes
- import sys
- import argparse
- from argparse import ArgumentParser
- parser = ArgumentParser(description="Mail X", add_help=True)
- parser.add_argument('-c', '--content', type=str,
- required=True, help=u"Mail content")
- parser.add_argument('-s', '--subject', type=str,
- required=True, help=u"Mail subject")
- parser.add_argument('-f', '--fromer', type=str,
- required=True, help=u"Mail sender")
- parser.add_argument('--files', nargs='*',
- help=u"Mail attachments,Support for multiple files")
- args = parser.parse_args()
- # 第三方 SMTP 服务设置
- mail_host = ""
- mail_user = ""
- mail_pass = ""
- sender = ''
- receivers = [''] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
- def sendmail(content, subject, source, files=None):
- """ sendmail """
- msg = MIMEMultipart('related')
- msg['From'] = Header(source, 'utf-8')
- msg['To'] = Header("伟大的安全工程师们", 'utf-8')
- # subject = 'Python SMTP 邮件测试'
- msg['Subject'] = Header(subject, 'utf-8')
- message = MIMEText(content, 'plain', 'utf-8')
- msg.attach(message)
- if files:
- for file in files:
- ctype, encoding = mimetypes.guess_type(file)
- if ctype is None or encoding is not None:
- ctype = "application/octet-stream"
- maintype, subtype = ctype.split("/", 1)
- if maintype == "text":
- fp = open(file)
- # Note: we should handle calculating the charset
- attachment = MIMEText(fp.read(), _subtype=subtype)
- attachment.add_header(
- "Content-Disposition", "attachment", filename=file.split('/')[-1])
- fp.close()
- else:
- print("No Support File Type!")
- return 1
- msg.attach(attachment)
- try:
- smtpObj = smtplib.SMTP_SSL(mail_host, port=465)
- smtpObj.connect(mail_host) # 25 为 SMTP 端口号
- smtpObj.login(mail_user, mail_pass)
- smtpObj.sendmail(sender, receivers, msg.as_string())
- print "邮件发送成功"
- smtpObj.close()
- except smtplib.SMTPException:
- print "Error: 无法发送邮件"
- def main():
- # if len(sys.argv) == 4:
- # sendmail(sys.argv[1], sys.argv[2], sys.argv[3])
- # elif len(sys.argv) == 5:
- # sendmail(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
- # else:
- # print '请输入邮件内容,标题,发件人,附件'
- print(args)
- sendmail(args.content, args.subject, args.fromer, args.files)
- if __name__ == '__main__':
- main()
Add Comment
Please, Sign In to add comment