功能:发送的内容包括情话加插图,并推送对象所在城市的天气信息。内容格式为html格式。
文字来源:事先准备的文件SweetSentences.txt(中英文双语表白情话)
插图来源:事先准备的文件picture.txt(python在网上获取的精美图片链接)
效果图:
mail.py源码如下:
#!/usr/bin/python
#-*-coding:UTF-8-*-
import smtplib
import time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import urllib,urllib2
import re
import traceback
import os
import random
def acq_picture():
with open("/home/cc/python/mail/picture.txt",'r') as f:
list1 = f.readlines()
num = len(list1)
index = random.randint(0,num-1)
msg = list1[index]
print(type(msg))
return msg
def send_email(text):
cur_time = time.localtime(time.time())
print("===============%s===============" % cur_time)
mail_host='smtp.qq.com'
mail_user='**********'
mail_pass='**********'
sender = '**********@qq.com'
receivers= ['*******@qq.com','*******@qq.com']
print(receivers)
src = acq_picture()
print(type(text))
print(type(src))
try:
html = '<html><body>' + text + '<p><img src="' + src +'"></p></body></html>'
print(type(html))
#print(html)
except Exception as e:
print(e)
traceback.print_exe()
message = MIMEMultipart()
message.attach(MIMEText(html,'html','utf-8'))
message['Subject'] = 'DAILY EMAIL FROM CC'
message['From'] = sender
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host,587)
smtpObj.starttls()
smtpObj.login(mail_user,mail_pass)
smtpObj.sendmail(sender,receivers,message.as_string())
smtpObj.quit()
print('success')
except smtplib.SMTPException as e:
print('error',e)
def acq_sentence():
with open("/home/cc/python/mail/SweetSentence.txt",'r') as f:
list1 = f.readlines()
num = len(list1) // 2
index = random.randint(0,num-1) * 2
msg = list1[index] + "<br>" + list1[index + 1]
return msg.decode('utf-8')
def acq_weather():
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
url = "http://www.tianqi.com/shenzhen/"
try:
request = urllib2.Request(url,headers = headers)
response = urllib2.urlopen(request)
urlhtml = response.read()
except Exception as e:
raise e
re_page = re.compile(r'<dd class="name">.*?<h2>(.*?)</h2>.*?<dd class="week">(.*?)</dd>.*?<span>.*?<b>(.*?)</b>(.*?)</span>',re.S)
items = re_page.findall(urlhtml)
dic = {}
dic["城市"] = items[0][0]
dic["日期"] = items[0][1]
dic["天气"] = items[0][2]
dic["温度"] = items[0][3]
sweet_sentence = acq_sentence().encode('utf-8')
content = sweet_sentence + "<br>" + "-------------------------------------<br>" + "城市: " +dic["城市"] +"<br>" +"日期: " +dic["日期"] +"<br>" +"天气: " +dic["天气"] +"<br>" +"温度: " +dic["温度"]
send_email(content)
if __name__ == '__main__':
try:
acq_weather()
except Exception as e:
print(e)
#traceback.print_exe()
祝广大的程序员兄弟早日脱单!
帮忙给个赞!!!