看到一篇文章——定时给ta讲笑话,挺有趣的,
之前没有学过python,从网上下了个python3.4,把代码copy进去跑,老是有问题,这才知道python3.x和python2.x有很大不同。明显链接里面的是python2.x的
做了若干修改,终于能成功发送了。代码如下:
# -*- coding: utf-8 -*-'''Created on 2016年5月5日@author: mandala'''import urllib, json,sys,smtplibfrom urllib.request import *from email.mime.text import MIMEText#reload(sys)#sys.setdefaultencoding('utf-8')#避免中文编码问题mail_host="smtp.139.com" #设置服务器mail_user="***@139.com" #用户名mail_pass="***" #口令 mailto_list=['**@139.com'] #邮件接受者:手机号+@139.comdef send_mail(to_list,part1,sub,content): #to_list:收件人;sub:主题;content:邮件内容; me=part1+"<"+mail_user+">" #hello #me=part1 msg = MIMEText(content,_subtype='plain',_charset='utf-8')#创建一个实例,这里设置为纯文字格式邮件编码utf8 msg['Subject'] = sub #设置主题 #print(sub) #print(me) msg['From'] = me #设置发件人 msg['To'] = ";".join(to_list) try: s = smtplib.SMTP() #实例化 s.connect(mail_host) #连接smtp服务器 s.login(mail_user,mail_pass) #登陆服务器 s.sendmail(me, to_list, msg.as_string()) #发送邮件 s.close() return True except Exception as e: print('a'+str(e)) return False if __name__ == '__main__': appkey = "e2376cfbe3b27dff923ed61698839a67" url = 'http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_text?page=1' req = urllib.request.Request(url) req.add_header("apikey", appkey) resp = urllib.request.urlopen(req) content = resp.read() if(content): json_result = json.loads(content.decode()) content_list = json_result['showapi_res_body']['contentlist'] minlen = 10000 for item in content_list: if len(item['text'])