交房倒计时提醒邮件

2022-05-12  本文已影响0人  香山上的麻雀
# encoding=utf8
import random
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from datetime import datetime, timedelta, date
import os
import time
import pytz
import requests
from zhdate import ZhDate
import json

today = datetime.fromtimestamp(int(time.time()), pytz.timezone('Asia/Shanghai')).date()
tomorrow = today + timedelta(days=1)
format_today = today.strftime('%Y年%m月%d日')
dead_line = date(2023, 9, 30)
duration = (dead_line - today).days
filename = 'day' + str(duration) + '.png'
fontsFolder = '.'
receivers = ['xxx@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
holidays = [{"2022-06-03": "端午节假期"}, {"2022-09-10": "中秋节假期"},
            {"2022-10-01": "国庆节假期"}, {"2023-01-01": "2023年元旦假期"}]


class remind_me:

    def send_mail(self):
        # 发件人邮箱
        sender = 'xxxx@gmail.com'
        sender_password = 'xxxxx'

        mail_msg = """
        <html><body>
        <img src="cid:image1" alt="image1" align="center" width=100% >
        </body></html>
        """
        msg = MIMEMultipart()
        content = MIMEText(mail_msg, _subtype='html', _charset='utf8')
        msg.attach(content)

        # 构建并添加图像对象
        img1 = MIMEImage(open(filename, 'rb').read(), _subtype='octet-stream')
        img1.add_header('Content-ID', 'image1')
        msg.attach(img1)

        msg['From'] = Header("提醒", 'utf-8')
        msg['To'] = Header("尊贵的5号院业主", 'utf-8')

        subject = '交房提醒'
        msg['Subject'] = Header(subject, 'utf-8')

        # 构建并添加附件对象
        # 如果不想直接在邮件中展示图片,可以以附件形式添加
        # img = MIMEImage(open('day1.png', 'rb').read(), _subtype='octet-stream')
        # img.add_header('Content-Disposition', 'attachment', filename='day1.png')
        # msg.attach(img)

        try:
            smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
            smtpObj.ehlo()
            smtpObj.starttls()

            smtpObj.login(sender, sender_password)
            smtpObj.sendmail(sender, receivers, msg.as_string())
            print("success")
        except smtplib.SMTPException as e:
            print(e)
            print("Error: 无法发送邮件")

    def generate_picture(self):
        from PIL import Image, ImageDraw, ImageFont
        # warm_tips = ['家是幸福的港湾', '房是家庭的据点']

        for count_day in [duration]:  # 创建图像,设置图像大小及颜色
            im = Image.new('RGBA', (1000, 1800), (166, 12, 4, 255))
            draw = ImageDraw.Draw(im)  # 设置本次使用的字体

            font1 = ImageFont.truetype(os.path.join(fontsFolder, '华康俪金黑W8.TTF'), 420)
            font2 = ImageFont.truetype(os.path.join(fontsFolder, '方正兰亭刊黑_GBK.TTF'), 40)  # 计算各文本的放置位置
            font3 = ImageFont.truetype(os.path.join(fontsFolder, '方正兰亭刊黑_GBK.TTF'), 50)  # 计算各文本的放置位置
            
            txtSize_0 = draw.textsize(r'今 天 是 {}'.format(format_today), font2)
            pos_x_0 = (1000 - txtSize_0[0]) / 2

            date2 = ZhDate.from_datetime(datetime(today.year, today.month, today.day)).chinese()
            txtSize_00 = draw.textsize(f"农历{date2}", font2)
            pos_x_00 = (1000 - txtSize_00[0]) / 2
            
            txtSize_1 = draw.textsize('距 离 富田·九鼎华府 五 号 院 交 房', font3)
            pos_x_1 = (1000 - txtSize_1[0]) / 2
            txtSize_2 = draw.textsize('还 有', font3)
            pos_x_2 = (1000 - txtSize_2[0]) / 2
            txtSize_3 = draw.textsize('天', font3)
            pos_x_3 = (1000 - txtSize_3[0]) / 2
            txtSize_4 = draw.textsize(' '.join(warm_tips[0]), font2)
            pos_x_4 = (1000 - txtSize_4[0]) / 2
            txtSize_5 = draw.textsize(' '.join(warm_tips[1]), font2)
            pos_x_5 = (1000 - txtSize_5[0]) / 2  # 设置文本放置位置,居中

            draw.text((pos_x_0, 100), r'今 天 是 {}'.format(format_today), fill=(217, 217, 217, 255), font=font2)
            draw.text((pos_x_00, 200), f"农历 {date2}", fill=(217, 217, 217, 255), font=font2)
            draw.text((pos_x_1, 300), '距 离 富田·九鼎华府 五 号 院 交 房', fill=(217, 217, 217, 255), font=font3)
            draw.text((pos_x_2, 400), '还 有', fill=(217, 217, 217, 255), font=font3)
            draw.text((pos_x_3, 1010), '天', fill=(217, 217, 217, 255), font=font3)
            draw.text((pos_x_4, 1210), ' '.join(warm_tips[0]), fill=(137, 183, 109, 255), font=font2)
            draw.text((pos_x_5, 1300), ' '.join(warm_tips[1]), fill=(137, 183, 109, 255), font=font2)  # 绘制线框
            draw.line([(20, 20), (980, 20), (980, 1780), (20, 1780), (20, 20)], fill=(217, 217, 217, 255),
                      width=5)  # 设置变化的文本属性
            txtSize_6 = draw.textsize(str(count_day), font1)
            pos_x_6 = (1000 - txtSize_6[0]) / 2
            draw.text((pos_x_6, 500), str(count_day), fill=(137, 183, 109, 255), font=font1)  # im.show()# 保存图像
            zz_weather = self.get_weather('郑州市')
            if zz_weather:
                draw.rectangle(((50, 1410), (950, 1750)), (166, 12, 4, 255), (137, 183, 109, 255), 2)
                forecasts = zz_weather['forecasts']
                address = zz_weather['address']
                draw.text((65, 1430), address + '天气:', fill=(217, 217, 217, 255), font=font2)
                for forecast in forecasts:
                    if forecast['date'] == today.__str__():
                        today_weather = f"今日: {forecast['dayWeather']} {forecast['nightTemp']}~{forecast['dayTemp']}"
                        draw.text((100, 1480), today_weather, fill=(217, 217, 217, 255), font=font2)
                    if forecast['date'] == tomorrow.__str__():
                        tomorrow_weather = f"明日: {forecast['dayWeather']} {forecast['nightTemp']}~{forecast['dayTemp']}"
                        draw.text((544, 1480), tomorrow_weather, fill=(217, 217, 217, 255), font=font2)
            bj_weather = self.get_weather('北京市')
            if bj_weather:
                # draw.rectangle(((50, 1450), (950, 1750)), (166, 12, 4, 255), (137, 183, 109, 255), 2)
                forecasts = bj_weather['forecasts']
                address = bj_weather['address']
                draw.text((65, 1530), address + '天气:', fill=(217, 217, 217, 255), font=font2)
                for forecast in forecasts:
                    if forecast['date'] == today.__str__():
                        today_weather = f"今日: {forecast['dayWeather']} {forecast['nightTemp']}~{forecast['dayTemp']}"
                        draw.text((100, 1580), today_weather, fill=(217, 217, 217, 255), font=font2)
                    if forecast['date'] == tomorrow.__str__():
                        tomorrow_weather = f"明日: {forecast['dayWeather']} {forecast['nightTemp']}~{forecast['dayTemp']}"
                        draw.text((544, 1580), tomorrow_weather, fill=(217, 217, 217, 255), font=font2)
            _count = 0
            _pos = 1630
            for i in range(len(holidays)):
                ds = [x for x in holidays[i].keys()][0]
                if ds > today.__str__():
                    ho_d = (date.fromisoformat(ds) - today).days
                    if ho_d > 0 and _count < 2:
                        _count += 1
                        holiday_1 = "".join(f"距离{holidays[i][ds]}还有 {ho_d} 天")
                        draw.text((65, _pos), holiday_1, fill=(217, 217, 217, 255), font=font2)
                        _pos += 60
            im.save(filename)

            
    def remind(self):
        self.generate_picture()
        self.send_mail()
        os.remove(filename)

        
    def get_weather(self, city):
        app_id = 'xxxx'  # 在www.mxnzp.com申请
        app_secret = 'xxxx' # 在www.mxnzp.com申请
        url_weather = 'https://www.mxnzp.com/api/weather/forecast/{city_name}?app_id={app_id}&app_secret={app_secret}'
        res = requests.get(url_weather.format(city_name=city, app_id=app_id, app_secret=app_secret))
        try:
            msg: str = json.loads(res.text)['msg']
            if msg and msg.__contains__('数据返回成功'):
                return json.loads(res.text)['data']
        except Exception:
            return None
        

if __name__ == '__main__':
    all_warm_tips = [['非淡泊无以明志', '非宁静无以致远'], ['长风破浪会有时', '直挂云帆济沧海'], ['穷则独善其身', '达则兼善天下'],
                     ['不经一番寒彻骨', '怎得梅花扑鼻香'], ['纸上得来终觉浅', '绝知此事要躬行'], ['贵有恒何必三更眠五更起', '最无益只怕一日曝十日寒'],
                     ['黑发不知勤学早', '白首方悔读书迟'], ['大鹏一日同风起', '扶摇直上九万里'], ['不畏浮云遮望眼', '自缘身在最高层'],
                     ['横看成岭侧成峰', '远近高低各不同'], ['⾐带渐宽终不悔', '为伊消得⼈憔悴'], ['去留⽆意,闲看庭前花开花落', '宠辱不惊,漫随天外云卷云舒'],
                     ['粗缯大布裹生涯','腹有诗书气自华'], ['山有木兮木有枝', '心悦君兮君不知'], ['但愿人长久', '千里共婵娟'], ['人生得意须尽欢', '莫使金樽空对月'],
                     ['两情若是久长时', '又岂在朝朝暮暮'], ['飞流直下三千尺', '疑是银河落九天'], ['古人学问无遗力', '少壮工夫老始成'],
                     ['宠辱不惊看庭前花开花落', '去留无意望天上云卷云舒'], ['疏影横斜水清浅', '暗香浮动月黄昏'], ['和风细动帘帷暖', '清露微凝枕簟凉'],
                     ['梨花满院飘香雪', '高楼夜静风筝咽'], ['入室许清风', '对饮惟明月'], ['有约不来过夜半', '闲敲棋子落灯花']]

    warm_tips = all_warm_tips[random.randint(0, len(all_warm_tips) - 1)]
    remind_me = remind_me()
    remind_me.remind()
上一篇 下一篇

猜你喜欢

热点阅读