PYTHON发送邮件
一,普通文本发送
import smtplib from email.mime.text import MIMEText from email.header import Header sender = '发送邮箱' password = "发送邮箱密码" receivers = ['收件人'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 mail_msg = """ <p>Python 邮件发送测试...</p> <p><a href="http://www.baidu.com">这是一个链接</a></p> """ message = MIMEText(mail_msg, 'html', 'utf-8') message['From'] = Header("测试测试", 'utf-8') message['To'] = Header("测试", 'utf-8') subject = 'Python SMTP 邮件测试' message['Subject'] = Header(subject, 'utf-8') try: server = smtplib.SMTP_SSL("smtp.qq.com", 465) # 发件人邮箱中的SMTP服务器,端口是25 server.login(sender, password) # 括号中对应的是发件人邮箱账号、邮箱密码 server.sendmail(sender, receivers, message.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件 server.quit() # 关闭连接 print("邮件发送成功") except smtplib.SMTPException: print("Error: 无法发送邮件")
二、带图片发送
import smtplib from email.header import Header from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart # 发件人地址 from_addr = "发送邮箱" password = "发送邮箱密码" to_addr = ["收件邮箱"] smtp_server = "smtp.qq.com" msg = MIMEMultipart('related') message = """ <p>Python 邮件发送测试...</p> <p><a href="http://www.baidu.com">这是一个链接</a></p> <p>图片演示</p> <p><img src="cid:image1"></p> """ msg['From'] = Header("测试", 'utf-8') msg["To"] = Header("测试", 'utf-8') msg["Subject"] = Header("测试邮件发送-添加附件", 'utf-8').encode() msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) msgAlternative.attach(MIMEText(message, 'html', 'utf-8')) fp = open('data/1.jpg', 'rb') msgImag = MIMEImage(fp.read()) fp.close() msgImag.add_header('Content-ID', '<image1>') msg.attach(msgImag) server = smtplib.SMTP_SSL(smtp_server, 465) server.login(from_addr, password) server.sendmail(from_addr, to_addr, msg.as_string()) server.quit()
三、附件发送
import smtplib from email.header import Header from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart # 发件人地址 from_addr = "发件邮箱" password = "发件邮箱密码" to_addr = ["收件邮箱"] smtp_server = "smtp.qq.com" msg = MIMEMultipart() msg['From'] = Header("测试", 'utf-8') msg["To"] = Header("测试", 'utf-8') msg["Subject"] = Header("测试邮件发送-添加附件", 'utf-8').encode() msg.attach(MIMEText("这是python测试邮件发送,并添加了附件", 'plain', 'utf-8')) att1 = MIMEText(open('data/testemail2.txt', 'rb').read(), 'base64', 'utf-8') att1['Content-Type'] = 'application/octet-stream' att1['Content-Disposition'] = 'attachment;filename="testemail2.txt"' msg.attach(att1) att2 = MIMEText(open('data/testemail.txt', 'rb').read(), 'base64', 'utf-8') att2['Content-Type'] = 'application/octet-stream' att2['Content-Disposition'] = 'attachment;filename="testemail.txt"' msg.attach(att2) server = smtplib.SMTP_SSL(smtp_server, 465) server.login(from_addr, password) server.sendmail(from_addr, to_addr, msg.as_string()) server.quit()
s