1 #构建对象时,第一个是邮件正文,第二个发送类型,plain表示纯文本,最后使用utf-8保证多语言兼容 2 #如果需要发送html的话,就把plain改为html------>内容使用html构造便可 3 #然后通过SMTP发出去: 4 from email.header import Header; 5 6 msg=MIMEText('<a href=''>哈哈</a>','html','utf-8'); 7 #msg['Subject'] = Header("标题", 'utf-8') 8 #SMTP 9 #msg['from'] = 'XXX@163.com' 10 #msg['to'] = 'XXX@QQ.com' 11 from_addr=input('FROM:'); 12 password=input('PASSWORD:');#163的授权码 13 #输入收件人地址 14 to_addr=input('TO:'); 15 #输入smtp服务器地址smtp.163.com 16 smtp_server=input('SMTP_SERVER:'); 17 msg['from']=from_addr; 18 msg['to']=to_addr; 19 20 #标题 21 msg['subject']=Header('来自XXX的问候','utf-8').encode(); 22 23 import smtplib; 24 server=smtplib.SMTP(smtp_server,25);#默认是25 25 server.set_debuglevel(1);#打印出smtp和服务器交互的所有信息,也可以不用 26 server.connect(smtp_server); 27 server.login(from_addr, password); 28 server.sendmail(from_addr,to_addr, msg.as_string()); 29 server .quit(); 30 print('成功'); 31 32 33 #server.login(from_addr,password); 34 #server.sendmail(from_addr,[to_addr],msg.as_string()); 35 #server.quit();
======================
以下为完整的封装代码
1 #封装发送邮箱代码 2 3 import re; 4 from email.mime.text import MIMEText; 5 from email.header import Header; 6 import smtplib; 7 8 def sendmail(textTitle,froms,tos,smtp_server,pwd,codes): 9 msg=MIMEText(textTitle,'plain','utf-8'); 10 msg['subject']=Header('报告','UTF-8').encode(); 11 msg['from']=froms; 12 msg['to']=tos; 13 smtp_server=smtp_server; 14 pwd=pwd; 15 server = smtplib.SMTP(smtp_server, codes); 16 server.connect(smtp_server); 17 server.login(msg['from'],pwd ); 18 server.sendmail(msg['from'],msg['to'],msg.as_string()); 19 server.quit(); 20 return 'success';