Last active
November 8, 2018 03:01
-
-
Save Loveforkeeps/0c8df4a3c34a9fa4c017456dd607ed05 to your computer and use it in GitHub Desktop.
python实现的支持参数化多附件的Mail发送工具
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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,os | |
import argparse | |
from argparse import ArgumentParser | |
# 获取脚本位置路径 | |
path = os.path.split(os.path.realpath(__file__))[0] + '/' | |
os.chdir(path) | |
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 = [''] | |
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(): | |
sendmail(args.content, args.subject, args.fromer, args.files) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment