Python应用-完成简单邮件发送功能

    项目中有时候需要用脚本来自动发送邮件,而用Python来发送邮件十分的方便,代码如下:

   

#!/usr/bin/python
#coding:utf-8
import smtplib  
from email.mime.text import MIMEText  # 引入smtplib和MIMEText
 
 
smtp_info = {
    "host":"smtp.163.com", # 设置发件服务器地址
    "port": 25, # 设置发件服务器端口号。注意,这里有SSL和非SSL两种形式
    "user":"user@163.com", # 设置发件邮箱
    "pass":"password" # 设置发件邮箱的密码
}
 
mail_to_list=["aaaa@qq.com","bbbb@qq.com"]
mail_title='The first mail'
 
 
body = '<h1>Hi</h1><h2/>你好,好久不见,别来无恙!</h2>' #设置邮件正文,这里支持HTML
 
 
 
def send_mail(mail_title,mail_list,body):
    
   msg=MIMEText(body,'html','utf-8')
   msg['Subject'] = mail_title  # 设置邮件标题
   msg['From'] = smtp_info.get('user')  # 设置发送人
   msg['To'] = u";".join(mail_to_list).encode('utf-8') # 设置接收人
    
   try:
       s=smtplib.SMTP() # 注意!如果是使用SSL端口,这里就要改为SMTP_SSL
       s.connect(smtp_info.get('host'),smtp_info.get('port'))
       s.login(smtp_info.get('user'),smtp_info.get('pass')) # 登陆邮箱
       s.sendmail(smtp_info.get('user'), mail_to_list, msg.as_string())  # 发送邮件  
       return True 
   except Exception, e:  
       print str(e)  
       return False
   finally:
       s.close()
    
 
if __name__=='__main__':
   if send_mail(mail_title,mail_to_list,body):  
      print "send email success"  
   else:  
      print "send email fail"

  

posted @ 2018-03-12 08:54  圆柱模板  阅读(186)  评论(0编辑  收藏  举报