python 发邮件

尽管在百度里,可以查到很多关于python发送邮件的代码,但是并非每个代码都好用,避免搞错,留下一个正确的发送代码

#!/usr/bin/env python
#-*- coding:UTF-8 -*-
import smtplib  
from email.mime.text import MIMEText  
from email.header import Header  
from email.mime.multipart import MIMEMultipart
 
 
sender = 'xxxxxxx@163.com'  
receiver = 'xxxxx@163.com'  
subject = 'python email test中文'  
smtpserver = 'smtp.163.com'  
username = 'xxxxxx'  
password = 'xxxxxx'  
 
sender = "xxxxxx@163.com"
rcpt = "xxxxxxxx@163.com"
msg = MIMEMultipart('alternatvie')
msg['Subject'] = Header("测试发信","utf-8") #组装信头
msg['From'] = r"%s <pywugwlaowu@163.com>" % Header("老吴","utf-8") #使用国际化编码
msg['To'] = rcpt
 
#html = open('html.tpl').read() #读取HTML模板
html = '<font color=red>name is ge哈哈</font>'
html_part = MIMEText(html,'html') #实例化为html部分
html_part.set_charset('utf-8') #设置编码
msg.attach(html_part) #绑定到message里
 
try:
    s = smtplib.SMTP('smtp.163.com') #登录SMTP服务器,发信
    s.login('xxxx','xxxxxx')
    s.sendmail(sender,rcpt,msg.as_string())
except Exception,e:
    print 
print 'OK Ha'
 
 
 
'''
#发出来不能显示邮件正文
msg = MIMEText('what are you','text')#中文需参数‘utf-8’,单字节字符不需要  //发送不显示正文
 
msg['Subject'] = Header(subject, 'utf-8')  
msg['From'] = sender   
msg['To'] = receiver
 
smtp = smtplib.SMTP()  
smtp.connect('smtp.163.com')  
smtp.login(username, password)  
smtp.sendmail(sender, receiver, msg.as_string())  
smtp.quit()  
print 'OK'
'''


This entry was posted in Python and tagged , . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/python-email-send/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.
2020.03.24 评论已经全局关闭,有事加QQ聊天