学python要慎重,真的,因为业界很多的书用的语句都是python 2.7。对于我这种无论在windows还是linux上都是安装3.5的忠实用户,看书不难操作难,因为好多的句法要现反应。


python 2.7和python 3.5上发送邮件是不同的,在python 3.5上实现发送邮件的语句是这样的:

#!/usr/bin/env python        #python环境地址
import smtplib          #加载电邮模块smtplib
import email.mime.multipart      #加载multipart
import email.mime.text         #加载mime.text,即纯文本 
      
msg=email.mime.multipart.MIMEMultipart()  
msg['from']='chenx3314@sina.com'      #发送端地址
msg['to']='chenx1242@163.com'          #接受端地址
msg['subject']='这是一个python发送的纯文本邮件'      #邮件的标题
content="""                    
        妈妈:
         厨房里的菜刀我拿走了,不要问我去哪里,这个世界需要我!
            我是天神
    """                    #以上是邮件的内容
txt=email.mime.text.MIMEText(content)  
msg.attach(txt)  
      
smtp=smtplib  
smtp=smtplib.SMTP()              #创建一个SMTP对象
smtp.connect('smtp.sina.com','25')      #使用connect方法链接到新浪邮件服务器的25号端口
smtp.login('chenx3314@sina.com','对应的邮箱密码')      #登入发送端需要账号验证
smtp.sendmail('chenx3314@sina.com','chenx1242@163.com',str(msg))      #这句话才是邮件发送,括号内的顺序是(发送端,接收端,文件内容)
smtp.quit()                  #断开smtp链接

:wq 保存之后,#python  了它,邮箱那边的显示就是成功的。

51cto昨天下午上传本地图片屡次出现“网络链接有误”,不知道什么原因,所以图片欠奉。


还有一种写法,思路比较简单直白,而且无论是3.5还是2.7都可以启动,而且最重要的是,这个脚本里从头到尾都不用输入密码!如下图。

#!/usr/bin/env python

import smtplib

sender = 'chenx1242@163.com'
receiver = ['124208739@qq.com']        #接收方不可以是网易邮箱,会被吃掉

message = """From: From Person <chenx1242@163.com>
To: To Person <124208739@qq.com>
Subject: SMTP e-mail test

This is a test e-mail message.
if you see this e-mail,that means you were successful.
"""

smtpObj = smtplib.SMTP('localhost')    #这里一定要有localhost
smtpObj.sendmail(sender, receiver, message)
print "Successfully sent email"
smtpObj.quit()
#except SMTPException:            #这个语句在python 2.7里不识别,但是在3.5里识别
#   print "Error: unable to send email"


这里直接也补充一个2.7的邮件发送脚本,在linux使用要先说明utf-8。

# -*- coding: UTF-8 -*-
import sys, os, re, urllib, urlparse
import smtplib
import traceback
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
password = "******"
fromaddr = "123456@qq.com"
smtpaddr = "smtp.qq.com"
toaddrs = ["654321@qq.com"]
def sendemail(title,content):
    mail_msg = MIMEMultipart()
    if not isinstance(title,unicode):
        title = unicode(title, 'utf-8')
    mail_msg['Subject'] = title
    mail_msg['From'] =fromaddr
    mail_msg['To'] = ','.join(toaddrs)
    mail_msg.attach(MIMEText(content, 'html', 'utf-8'))
    try:
        s = smtplib.SMTP_SSL("smtp.qq.com", 465)
        s.login(fromaddr,password)  #登录邮箱
        s.sendmail(fromaddr, toaddrs, mail_msg.as_string()) #发送邮件
        s.quit()
        return True
    except Exception,e:
        return flase
if sendemail(sys.argv[1], sys.argv[2]):
    print "邮件已发送!"
else:
    print "邮件发送失败!"