Python发送邮件

Python  /  houtizong 发布于 2年前   209
一、直接调用命令行发送邮件(以及shell中sendEmail)
问题:主题为中文时乱码

主题乱码,网上找了很多,基本上可以确认是头文件编码的问题,通过对主题进行base64编码可以解决这个问题,实现如下:

      # 发送email,username用户名,subject主题,text内容      def send_email(self,username,subject,text):          # 邮件内容为utf-8格式          text = text.encode('utf-8')          # 主题需要进行base64编码在转成utf8,注意后面这个strip,否则又出现一个换行符          subject = "=?UTF-8?B?%s?=" % base64.encodestring(subject).strip()          cmd = "/usr/bin/sendEmail -f [email protected] -t %s  -o message-charset=utf-8 -u \"%s\"  -m \"%s\" " % (username,subject,text)          try:              rt = os.popen(cmd).read().split()              return True          except Exception,e:              return False


直接用shell发送邮件的代码如下
subject=`echo -n 任务异常 | base64`test_time=20130123sendEmail -f [email protected] -t [email protected]  -o message-charset=utf-8 -u "=?UTF-8?B?${subject}?="  -m "已经存在任务,${test_time}的任务取消进行"


补充:  正文的换行符是
 \n


如果是ssh调用其他的邮件服务器来发邮件,命令要ssh命令要用双引号括起来,否则换行字符不识别
 ssh root@**** "sendemai -o ...."


二、使用SMTP协议发送邮件

        newusers = '[email protected];[email protected]'        newccs  = '[email protected];[email protected]'        text = '测试邮件'        mail_host = 'smtp.xxx.com'        mail_user = 'xxx_service'        mail_user_full = '[email protected]'        mail_pwd = '密码'        mail_bcc = ''        #表头信息        msg = MIMEText(text,'base64', 'utf-8')        msg['From'] = mail_user_full        msg['Subject'] = subject        msg['To'] = newusers        msg['Cc'] = newccs        msg['Bcc'] = ''                try:            s = smtplib.SMTP()            s.connect(mail_host,'25')            #login            s.login(mail_user,mail_pwd)            #send mail            print newusers            print newccs            print msg.as_string()            #  邮件人发送和抄送统一放在一起发送,需要在上面的标头信息中进行区分s.sendmail(mail_user_full,newusers.split(';')+newccs.split(';')+mail_bcc.split(";"),msg.as_string())            s.close()            print 'success'            # print rt            return True        except Exception,e:            # print 'email error'            print e            return False

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客