标签:发送邮件 sendmail 链接 http utf-8 格式 src host omr
1、文本邮件发送
import smtplib from email.mime.text import MIMEText from email.utils import formataddr my_sender = ‘477931661@qq.com‘ # 发件人邮箱账号 my_pass = ‘deyoxpsfnhomcabe‘ # 发件人邮箱密码 my_user = ‘477931661@qq.com‘ # 收件人邮箱账号,我这边发送给自己 def mail(): ret = True try: msg = MIMEText(‘填写邮件内容‘, ‘plain‘, ‘utf-8‘) msg[‘From‘] = formataddr(["FromRunoob", my_sender]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号 msg[‘To‘] = formataddr(["FK", my_user]) # 括号里的对应收件人邮箱昵称、收件人邮箱账号 msg[‘Subject‘] = "菜鸟教程发送邮件测试" # 邮件的主题,也可以说是标题 server = smtplib.SMTP_SSL("smtp.qq.com", 465) # 发件人邮箱中的SMTP服务器,端口是25 server.login(my_sender, my_pass) # 括号中对应的是发件人邮箱账号、邮箱密码 server.sendmail(my_sender, [my_user, ], msg.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件 server.quit() # 关闭连接 except Exception: # 如果 try 中的语句没有执行,则会执行下面的 ret=False ret = False return ret ret = mail() if ret: print("邮件发送成功") else: print("邮件发送失败")
2、携带附件发送
import smtplib from email.mime.text import MIMEText from email.header import Header from email.mime.multipart import MIMEMultipart sender = ‘477931661@qq.com‘ # 发件人的邮件地址 password = ‘deyoxpsfnhomcabe‘ # 发件人的客户端密码 host = ‘smtp.qq.com‘ # 发件人用的邮件服务器 receivers = [‘477931661@qq.com‘,‘524928525@qq.com‘] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 meg_text = ‘‘‘ <h1>这个是大标题</h1> <a href=https://xwmdream.cn>这个是链接</a> <p>这个邮件有附件</p> ‘‘‘ # 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码 message = MIMEMultipart() # 邮件正文内容 message.attach(MIMEText(meg_text, ‘html‘, ‘utf-8‘)) message[‘From‘] = Header("王晨~", ‘utf-8‘) # 内容中显示的发件人 message[‘To‘] = Header("先生/女士~", ‘utf-8‘) # 内容中显示的收件人 message[‘Subject‘] = Header(‘主题:测试~‘, ‘utf-8‘) # 邮件的题目 # 构造附件1,传送当前目录下的 test.txt 文件 att1 = MIMEText(open(‘test.txt‘, ‘rb‘).read(), ‘base64‘, ‘utf-8‘) att1["Content-Type"] = ‘application/octet-stream‘ # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 att1["Content-Disposition"] = ‘attachment; filename="123.txt"‘ message.attach(att1) # # 构造附件2,传送当前目录下的 runoob.txt 文件 # att2 = MIMEText(open(‘test/test.mp3‘, ‘rb‘).read(), ‘base64‘, ‘utf-8‘) # att2["Content-Type"] = ‘application/octet-stream‘ # att2["Content-Disposition"] = ‘attachment; filename="two.mp3"‘ # message.attach(att2) try: smtpObj = smtplib.SMTP_SSL() # 这个点要注意 smtpObj.connect(host) smtpObj.login(sender, password) # 邮箱登录 smtpObj.sendmail(sender, receivers, message.as_string()) print("邮件发送成功") except smtplib.SMTPException as e: print("Error: 发送邮件产生错误") print(e) smtpObj.close()
标签:发送邮件 sendmail 链接 http utf-8 格式 src host omr
原文地址:https://www.cnblogs.com/nick477931661/p/9111922.html