本帖最后由 GLH20220313 于 2023-7-26 21:45 编辑
# 添加附件函数
def add_att(msg, file_path, filename):
att = MIMEText(open( file_path,'rb').read(),'base64','utf-8') # rb以二进制方式读取
att["Content-Type"] = 'application/octet-stream'
att.add_header('Content-Disposition', 'attachment', filename = filename)
#将附件添加到MIMEMultipart中
msg.attach(att)
def send_email_test():
mail = {
'host':'smtp.XXXXX.com',
'user':'XXX@XXX.com',
'password':'******'
}
sender = mail['user']
receivers = '111@111.com' #单个收件人
# receivers = '111@111.com,222@222.com' #多个收件人
subject = '邮件来了'
nickname = '我是昵称'
message = MIMEMultipart()
message['From'] = '%s <%s>' % (Header(nickname , 'UTF-8'), sender)
message['To'] = Header(receivers, 'gb2312')
message['Subject'] = Header(subject).encode()
message['Message-id'] = email.utils.make_msgid()
message["Accept-Language"]="zh-CN"
message["Accept-Charset"]="ISO-8859-1,utf-8"
msg = '''
<html>
<h2>Hello</h2>
</html>
'''
html = MIMEText(msg, _subtype='html', _charset='UTF-8') # 发送HTML邮件
message.attach(html) # 添加
# 添加当前目录下附件1.xlsx作为邮件附件
file_path = os.path.join('附件1.xlsx')
file_name = '邮件显示附件名.xlsx'
add_att(message , file_path , file_name)
smtp = smtplib.SMTP() # 使用 SSL 连接smtp服务器,否则使用.SMTP
smtp.connect(mail['host'], 25) # 主机, 端口, 如果使用SSL为465, 否则 25
smtp.login(mail['user'], mail['password']) # 用户名, 密码
smtp.sendmail(sender, receivers, message.as_string()) # 单个收件人
# smtp.sendmail(sender, receivers.split(','), message.as_string()) # 多个收件人
smtp.quit()
print('完成邮件发生任务')
|