python 发送邮件及附件
作者:互联网
使用python发送邮件并携带附件
#!/usr/bin/env python3 from smtplib import SMTP_SSL from email.mime.text import MIMEText from email.header import Header from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication import os def send_email(receiver): sender = 'Yonge <xxxxxxxx@126.com>' content = f"邮件内容" fileName = '发送后邮件显示的附件名称' file_dir = '附件绝对路径' file_msg = MIMEApplication(open(file_dir, 'rb').read()) file_msg.add_header('Content-Disposition', 'attachment', filename=fileName) message = MIMEMultipart() # 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码 message.attach(MIMEText(content, 'html', 'utf-8')) message.attach(file_msg) message['Subject'] = Header('这是主题', 'utf-8') message['From'] = sender # 发送者 message['To'] = receiver # 接收者 try: smtpObj = SMTP_SSL('smtp.126.com') smtpObj.login(user='xxxxxxxx@126.com', password='HKFK*********WGGBVD') smtpObj.sendmail(sender, receiver, str(message)) smtpObj.quit() print('邮件发送成功!') except Exception as e: print('发送失败' +str(e)) if __name__ == '__main__': send_email('XXXXXXXX@qq.com')
标签:__,python,smtpObj,file,附件,import,message,email,邮件 来源: https://www.cnblogs.com/outsrkem/p/13111983.html