企业微信发送短信代码示例
代码示例:
# -*- coding: utf-8 -*-
def send_email(email_user, email_pas, address, email_name, address_name, email_server, email_port, email_header,
email_object, affix_path=None):
"""
发送短信模块
email_user: 发件人账号
email_pas: 发件人密码
address: 收件人
email_name: 发件人称呼
address_name: 收件人称呼
email_server: 邮箱服务器
email_port: 邮箱端口
email_header: 邮箱主题
email_object: 邮箱正文
affix_path: 附件路径
"""
try:
# 邮件内容
msg = MIMEMultipart()
# 正文
part_text = MIMEText(email_object, 'plain', 'utf-8')
msg.attach(part_text)
# 括号里的对应发件人邮箱昵称、发件人邮箱账号
msg['From'] = formataddr((email_name, email_user))
# 括号里的对应收件人邮箱昵称、收件人邮箱账号
msg['To'] = formataddr((address_name, address))
# 邮件的主题
msg['Subject'] = email_header
# 添加附件
if affix_path is not None:
filename = os.path.basename(affix_path) # 获取上传的文件名
part = MIMEApplication(open(r'{}'.format(affix_path), 'rb').read())
part.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(part)
# SMTP服务器,腾讯企业邮箱端口是465,腾讯邮箱支持SSL(不强制), 不支持TLS
# qq邮箱smtp服务器地址:smtp.qq.com,端口号:456
# 163邮箱smtp服务器地址:smtp.163.com,端口号:25
server = smtplib.SMTP_SSL(email_server, email_port)
# 登录服务器,括号中对应的是发件人邮箱账号、邮箱密码
server.login(email_user, email_pas)
# 发送邮件,括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
server.sendmail(email_user, [address, ], msg.as_string())
# 关闭连接
server.quit()
# 如果 try 中的语句没有执行,则会执行下面的 ret=False
return True
except Exception:
return False