Last active
May 3, 2018 13:26
-
-
Save wolfhong/e7f81257ad8f5f75382d120c6772966b to your computer and use it in GitHub Desktop.
send_email.py
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 -*- | |
""" | |
brief 发送邮件,不依赖第三方库. py2 | |
""" | |
import socket | |
import smtplib | |
import mimetypes | |
import email | |
FROM_ADDR = "" # 输入你自定义的 | |
SMTP_SERVER = "" # 输入你自定义的 | |
SMTP_PORT = 465 # 输入你自定义的 | |
SMTP_USER = FROM_ADDR # 输入你自定义的 | |
SMTP_PASSWD = "" # 输入你自定义的密码 | |
USE_SSL = 0 | |
Config = { | |
'email': { | |
'from_addr': FROM_ADDR, | |
'smtp_server': SMTP_SERVER, | |
'smtp_port': SMTP_PORT, | |
'smtp_user': SMTP_USER, | |
'smtp_passwd': SMTP_PASSWD, | |
'use_ssl': USE_SSL, | |
} | |
} | |
def unicode2str(string, encoding='utf-8'): | |
if isinstance(string, unicode): | |
return string.encode(encoding, 'replace') | |
return str(string) | |
def send_mail(to_list, subject, text, att=None): | |
""" | |
@brief 发邮件的函数 | |
@param text 邮件的正文 | |
@param to_list 邮件接收对象 | |
@param subject 邮件主题 | |
@param att 附件,非必须 | |
""" | |
to_list = to_list[:] | |
att = att or [] | |
subject = unicode2str(subject) | |
text = unicode2str(text) | |
# date_hostname = " [%s]" % (socket.gethostname().replace('.fwmrm.net', '')) | |
# subject += date_hostname | |
cfg = Config['email'] | |
# 邮件设置发送方,接收方,主题,日期 | |
msg = email.MIMEMultipart.MIMEMultipart('related') | |
msg.add_header('From', cfg['from_addr']) | |
msg.add_header('To', email.Utils.COMMASPACE.join(to_list)) | |
msg.add_header('Date', email.Utils.formatdate(localtime=True)) | |
msg.add_header('Subject', subject) | |
msg.attach(email.MIMEText.MIMEText("<pre>%s</pre>" % text, 'html')) | |
# begin att | |
for (filename, bytes) in att: | |
ctype, encoding = mimetypes.guess_type(filename) | |
if ctype is None or encoding is not None: | |
ctype = 'application/octet-stream' | |
maintype, subtype = ctype.split('/', 1) | |
mbase = email.MIMEBase.MIMEBase(maintype, subtype) | |
mbase.set_payload(bytes) | |
email.Encoders.encode_base64(mbase) | |
mbase.add_header('Content-disposition', 'attachment', filename=filename) | |
msg.attach(mbase) | |
server = smtplib.SMTP() | |
server.connect(cfg['smtp_server']) | |
if cfg['smtp_user']: | |
server.login(cfg['smtp_user'], cfg['smtp_passwd']) | |
server.sendmail(cfg['from_addr'], to_list, msg.as_string()) | |
server.quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment