python 定时给女朋友发QQ邮件

1-安装库

pip install PyEmail 或
pip install email -i https://pypi.tuna.tsinghua.edu.cn/simple/

pip install xpinyin -i http://pypi.douban.com/simple --trusted-host pypi.douban.com

pip install pymysql

pip install requests

pip install lxml

2-qq邮箱获取授权码

pc的web上登入qq邮箱,点击设置
在这里插入图片描述
点击账户
在这里插入图片描述
往下拉到,开启服务

在这里插入图片描述
在这里插入图片描述
然后就可以得到授权码了
在这里插入图片描述

3-配置文件

config.txt

# 发件人名字
Sender_name = ''

# 收件人名字
Attn_name = ''

# 邮件标题
Subject = '宝贝,早上好~'

# 发件方QQ邮箱
Sender_mail = ''

# 接收方QQ邮箱,可以写多个        ['QQ邮箱账号']
Receive_mail = ['']

# QQ邮箱的授权码
Authorization_code = ''

# 城市
City = ''

# 在一起的时间         '年-月-日'
Together_time = ''

# 女孩的生日时间
Girl_bday = ''

# 男孩的生日时间         '年-月-日'
Boy_bday = ''

# 设置每天发送邮件的时间   '小时-分钟'
Send_time = '07-00'

love_ana.txt

('a bold attempt is half success.', '勇敢的尝试是成功的一半。')
('A great ship asks deep waters.', '大船要走深水。')
('A little of every thing is nothing in the main.', '每事浅尝辄止,事事都告无成。')
('A man"s best friends are his ten fingers', '人的朋友是自己的十个手指。')
('Achievement provides the only real pleasure in life.', '有所成就是人生唯一的真正乐趣。')
('Action speak louder than words.', '行动胜于言语!')
('Actions speak louder that words', '事实胜于雄辩')
('Believe in yourself.', '相信你自己!')
('better late than never.', '只要开始,虽晚不迟。')
('Better say nothing than nothing to the purpose.', '话不中肯,不如不说。')
('Birth is much, but breeding is more.', '出身重要,教养更重要。')
('Do one thing at a time, and do well.', '一次只做一件事,做到最好!')
('Do what you say,say what you do.', '做你说过的,说你能做的')
("Don't give up and don't give in.", '不要放弃,不要言败!')
('East, west, home is best.', '银窝,不如自己的草窝。')
('Empty wagons rattle loudest.', '空车响声大。')
('Every journey begins with the first step.', '千里之行,始于足下。')
('Forget the pain, remember the cause of failure.', '忘记的疼苦,铭记失败的原因。')
('Get to another summit in your career。', '开创职业生涯的另一高峰。')
('go for it! just do it!', '加油!向前冲!做了再说!')
('He that once deceives is ever suspected.', '骗人一次,受疑一世。')
('He who makes no mistakes makes nothing.', '不犯错误者一事无成。')
('I can because i think i can.', '我行,因为我相信我行!')
('i know that my future is not just a dream.', '我知道我的未来不是梦。')
('I need him like I need the air to breathe', '我需要他,正如我需要呼吸空气。')
('If you get tired, learn to rest, not to quit.', '如果你累了,学会休息,而不是放弃。')
('Its not the gay coat that makes the gentleman.', '君子在德不在衣。')
('Jack of all trades and master of none.', '门门精通,样样稀松。')
('Judge not from appearances.', '人不可貌相,海不可斗量。')
('Just do it。', '向前冲。')
('Keep on going never give up.', '勇往直前, 决不放弃!')
('Kill two birds with one stone.', '一箭双雕。')
('Knowledge is power.', '知识就是力量。')
('Knowledge makes humble, ignorance makes proud.', '博学使人谦逊,无知使人骄傲。')
('Knowlege is power。', '知识就是力量。')
('Learn and live.', '活着,为了学习。')
('Learn to tolerate, to have a tolerant love!', '学会宽容,要有一颗宽容的爱心!')
('Learn to walk before you run.', '先学走,再学跑。')
('Let bygones be bygones.', '过去的就让它过去吧。')
('Let sleeping dogs lie.', '别惹麻烦。')
('Lies can never changes fact.', '谎言终究是谎言。')
('Lies have short legs.', '谎言站不长。')
('Life is half spent before we know what it is.', '人过半生,方知天命。')
('Life is not all roses.', '人生并不是康庄大道。')
('Life without a friend is death.', '没有朋友,虽生犹死。')
('Like author, like book.', '文如其人。')
('Like for like.', '一报还一报。')
('Like knows like.', '惺惺相惜。')
('Like tree, like fruit.', '羊毛出在羊身上。')
('Love is a fire which burns unseen.', '爱情是无形燃烧的火焰.')
('Love is the greatest refreshment in life.', '爱情是生活最好的提神剂.')
('Love me little and love me long.', '不求情意绵绵,但求天长地久.')
('Love means never having to say you are sorry.', '爱,意味着永不说后悔.')
('Love understands love; it needs no talk.', '相爱的心息息相通,无需用言语倾诉.')
('Love warms more than a thousand fires.', '爱情的炽热胜过千万团的火.')
('My heart belongs to you.', '我的心属于你')
('Never been young and frivolous.', '从来年少,一直轻狂。')
('Never forget to say “thanks”.', '永远不要忘了说“谢谢”!')
('Never say die.', '永不气馁!')
('Never say die。', '永不放弃。')
('Never to old to learn。', '活到老,学到老。')
('Never, never, never, never give up.', '永远不要、不要、不要、不要放弃。')
('Nothing for nothing.', '不费力气,一无所得。')
('Nothing is as good as it seems beforehand.', '期待比现实更美好。')
('Nothing is given so freely as advice.', '劝人最容易。')
('Nothing is impossible to a willing mind.', '世上无难事,只怕有心人。')
('Nothing seek, nothing find.', '无所求则无所获。')
('Nothing stake, nothing draw.', '不顶千里浪,哪来万斤鱼。')
('Nothing succeeds like success.', '一事如意,万事顺利。')
('Nothing venture, nothing have.', '不入虎穴,焉得虎子。')
('Of nothing comes nothing.', '无中不能生有。')
('One never lose anything by politeness', '讲礼貌不吃亏。')
('one today is worth two tomorrows.', '一个今天胜似两个明天。')
('ou mean the world to me.', '你对我来说是最重要的.')
('present love demands is love.', '爱所祈求的唯一礼物就是爱.')
('Pursue breakthroughs in your life。', '追求自我的突破。')
('Quitters never win and winners never quit.', '退缩者永无胜利,胜利者永不退缩。')
('Reading is always profitable', '开卷有益')
('Real dream is the other shore of reality.', '真正的梦就是现实的彼岸。')
('Say goodbye to the depravation of yesterday.', '告别昨日的颓废。')
('She who has never loved, has never lived.', '人活着总要爱一回')
('Some habits, however, was to change.', '有些习惯,无论如何都改不了.')
('Suffering is the most powerful teacher of life', '苦难是人生最伟大的老师。')
('Take away love, and our earth is a tomb.', '没有了爱,地球便成了坟墓.')
('The darkness is no darkness with thee.', '有了你,黑暗不再是黑暗.')
('The heart is large, and the self is small.', '心量要大,自我要小。')
('The ideal of life is to live an ideal life.', '生活的理想,就是为了理想的生活。')
('There is no remedy for love but to love more.', '治疗爱的创伤唯有加倍地去爱.')
('There is only one me in this world.', '在这个世界上,我是独一无二的')
('Try your best when you are young.Never regret.', '趁年轻,努力吧,别让自己太后悔。')
('Two heads are better than one.', '三个臭皮匠顶个诸葛亮。')
('Victory is the most tenacious man.', '胜利,是属于最坚韧的人。')
("Victory won't come to me unless I go to it.", '胜利是不会向我们走来的,我必须自己走向胜利。')
('We must strive for survival in the competition.', '人类要在竞争中求生存,更要奋斗。')
('Well begun is half done.', '好的开端是成功的一半。')
('Whatever is worth doing is worth doing well.', '任何值得做的事就值得把它做好!')
('When it has is lost, brave to give up.', '当拥有已经是失去,就勇敢的放弃。')
('Where there is a will, there is a way.', '有志者,事竟成。')
('With time, life sails against the current.', '时间顺流而下,生活逆水行舟。')
('You are not brave, no one for you to be strong.', '你不勇敢,没人替你坚强。')
('You are the greatest adventure of my life.', '你就是我生命中最大的冒险.')
('You belong to me.', '你是属於我的.')
('You cant make something out of nothing.', '巧妇难为无米之炊。')
('You light up my life.', '你照亮我的生命.')
('You sing the love song, I use sadness and.', '迩唱的那首情歌,我用悲伤和。')
("Youth gives you light please don't let it down.", '青春赋予你光芒 请你别让它失望。')
('Youth means limitless possilities。', '年轻就有无限的可能。')
('Zero in your target,and go for it.', '从零开始,勇往直前!')

4-代码实现

# -*- coding: UTF-8 -*-
'''
@Project :PM_Project 
@File    :SendLoveMail.py
@IDE     :PyCharm 
@Author  :Manba_77
@Date    :2022/9/30 23:36 
'''
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import datetime
import pymysql
import random
import requests
from xpinyin import Pinyin
from lxml import etree
import time


class love_mail():
    def __init__(self):
        # 读取参数文件
        with open('config.txt', 'r', encoding='utf-8') as f:
            read_result = f.readlines()
        # print(read_result)
        for result in read_result:
            # 发件人名字
            if 'Sender_name' in result:
                self.Sender_name = eval(result.split(' = ')[1].replace('\n', ''))
                print(f'发件人名字:{self.Sender_name}')
            # 发件人名字
            if 'Attn_name' in result:
                self.Attn_name = eval(result.split(' = ')[1].replace('\n', ''))
                print(f'收件人名字:{self.Attn_name}')
            # 邮件标题
            if 'Subject' in result:
                self.Subject = eval(result.split(' = ')[1].replace('\n', ''))
                print(f'邮件标题:{self.Subject}')
            # 发件方QQ邮箱
            if 'Sender_mail' in result:
                self.Sender_mail = eval(result.split(' = ')[1].replace('\n', ''))
                print(f'发件方QQ邮箱:{self.Sender_mail}')
            # 接收方QQ邮箱,可以写多个
            if 'Receive_mail' in result:
                self.Receive_mail = eval(result.split(' = ')[1].replace('\n', ''))
                print(f'接收方QQ邮箱:{self.Receive_mail}')
            # QQ邮箱的授权码
            if 'Authorization_code' in result:
                self.Authorization_code = eval(result.split(' = ')[1].replace('\n', ''))
                print(f'QQ邮箱的授权码:{self.Authorization_code}')
            # 城市
            if 'City' in result:
                self.City = eval(result.split(' = ')[1].replace('\n', ''))
                print(f'城市:{self.City}')
            # 在一起的时间
            if 'Together_time' in result:
                self.Together_time = eval(result.split(' = ')[1].replace('\n', ''))
                print(f'在一起的时间:{self.Together_time}')
            # 女孩的生日时间
            if 'Girl_bday' in result:
                self.Girl_bday = eval(result.split(' = ')[1].replace('\n', ''))
                print(f'女孩的生日时间:{self.Girl_bday}')
            # 男孩的生日时间
            if 'Boy_bday' in result:
                self.Boy_bday = eval(result.split(' = ')[1].replace('\n', ''))
                print(f'男孩的生日时间:{self.Boy_bday}')

    # 获取现在时间  '2022-9-28 星期二'self.time_now
    def get_time(self):
        # 现在的时间    年-月-日
        now = datetime.datetime.now().strftime("%Y-%m-%d").replace('-', '—')
        year = eval(now[:4])
        if now[5:6] == '0':
            month = eval(now[6:7])
        else:
            month = eval(now[5:7])

        if now[8:9] == '0':
            day = eval(now[9:])
        else:
            day = eval(now[8:])

        week_list = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
        # 现在周几
        weekday = week_list[datetime.date(year, month, day).weekday()]
        # 拼接时间      年-月-日 周几
        self.time_now = now + '    ' + weekday
        # return time_now

    # 获取天气气温  天气self.weather  最低气温self.low_air   最高气温self.high_air
    def get_weather_air(self):
        p = Pinyin()
        city = ''.join(p.get_pinyin(self.City).split('-'))
        url = 'https://www.tianqi.com/{}/'
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'}
        response = requests.get(url=url.format(city), headers=headers)
        text = response.text

        html = etree.HTML(text)
        # 天气
        self.weather = html.xpath('//dd[@class="weather"]/span/b/text()')[0]
        air = html.xpath('//dd[@class="weather"]/span/text()')[0]
        self.low_air = air.split(' ~ ')[0] + '℃'
        self.high_air = air.split(' ~ ')[1]

    # 计算相恋的时间  [天数,年,月,日]
    def count_love_time(self):
        # 在一起的时间
        start_data = self.Together_time
        # print(f'开始时间{start_data}')

        # 现在时间
        now_data = datetime.datetime.now().strftime("%Y-%m-%d")
        # print(f'现在时间{now_data}')

        # 一共的天数
        days_count = (datetime.datetime(int(now_data[:4]), int(now_data[5:7]), int(now_data[8:])) - datetime.datetime(int(start_data[:4]), int(start_data[5:7]), int(start_data[8:]))).days
        print(f'已经在一起{days_count}天')

        # 计算年份
        # print('年份:')
        year_1 = eval(start_data[:4])
        # print(year_1)

        year_2 = eval(now_data[:4])
        # print(year_2)

        # 计算月份
        # print('月份:')
        if start_data[5:6] == '0':
            month_1 = eval(start_data[6:7])
        else:
            month_1 = eval(start_data[5:7])
        # print(month_1)

        if now_data[5:6] == '0':
            month_2 = eval(now_data[6:7])
        else:
            month_2 = eval(now_data[5:7])
        # print(month_2)

        # 计算日
        # print('日:')
        if start_data[8:9] == '0':
            day_1 = eval(start_data[9:])
        else:
            day_1 = eval(start_data[8:])
        # print(day_1)

        if now_data[8:9] == '0':
            day_2 = eval(now_data[9:])
        else:
            day_2 = eval(now_data[8:])
        # print(day_2)

        # print('-' * 30)
        year_count = year_2 - year_1
        if month_2 - month_1 > 0:
            month_count = month_2 - month_1
            if day_2 - day_1 >= 0:
                day_count = day_2 - day_1
            else:
                day_count = day_1 - day_2
                month_count = month_count - 1
        elif month_2 - month_1 == 0:
            if day_2 - day_1 >= 0:
                day_count = day_2 - day_1
                month_count = 0
            else:
                day_count = day_1 - day_2
                year_count -= 1
                month_count = 11
        else:
            year_count -= 1
            month_count = month_1 - month_1
            if day_2 - day_1 >= 0:
                day_count = day_2 - day_1
            else:
                day_count = day_1 - day_2
                month_count -= 1

        print(f'{year_count}{month_count}{day_count}天')

        return [days_count, year_count, month_count, day_count]

    # 下一个纪念日还有多少天 self.verse
    def next_verse_days(self):
        start_data = self.Together_time
        # 现在时间
        now_data = datetime.datetime.now().strftime("%Y-%m-%d")
        # print(f'现在时间{now_data}')
        mounth_day = start_data[4:]
        y = int(now_data[:4])

        while True:
            year = str(y)
            next_data = year + mounth_day
            # print(f'下一个时间{next_data}')

            # 一共的天数
            days_count = (datetime.datetime(int(next_data[:4]), int(next_data[5:7]),int(next_data[8:])) - datetime.datetime(int(now_data[:4]),int(now_data[5:7]),int(now_data[8:]))).days

            if days_count >= 0:
                self.verse = days_count
                print(f'距离下一个周年纪念日还有{days_count}天')
                break
            y += 1

    # 距离下一个生日还有多少天
    def next_bday_days(self, bday_day):

        # 现在时间
        now_data = datetime.datetime.now().strftime("%Y-%m-%d")
        # 生日的月-日
        mounth_day = bday_day[4:]

        y = int(now_data[:4])

        while True:
            year = str(y)
            next_data = year + mounth_day
            # print(f'下一个时间{next_data}')

            # 一共的天数
            days_count = (datetime.datetime(int(next_data[:4]), int(next_data[5:7]),int(next_data[8:])) - datetime.datetime(int(now_data[:4]),int(now_data[5:7]),int(now_data[8:]))).days

            if days_count >= 0:
                print(f'距离下一个生日还有{days_count}天')
                return days_count
            y += 1

    # 获取每日语录
    def get_love_sayings(self):
        with open('love_ana.txt', 'r', encoding='utf-8') as f:
            l_a = f.readlines()
        l = len(l_a)

        m = random.choice([i for i in range(l)])

        love_sayings = eval(l_a[m].replace('\n', ''))
        print(love_sayings)
        return love_sayings

    # 发送
    def send_mail(self, mail_msg):
        # 邮件内容
        message = MIMEText(mail_msg, 'html', 'utf-8')

        # 发件人的名字,可以自由写
        message['From'] = Header(self.Sender_name, 'utf-8')

        # 发件人名字,可以自由填写
        message['To'] = Header(self.Attn_name, 'utf-8')

        # 邮件标题
        message['Subject'] = Header(self.Subject, 'utf-8')

        # 使用QQ邮箱的服务,发送邮件
        smtpObj = smtplib.SMTP_SSL("smtp.qq.com", 465)
        # 发送的QQ邮箱账号, QQ邮箱的授权码
        smtpObj.login(self.Sender_mail, self.Authorization_code)
        # 发送方QQ邮箱账号, 接受方QQ邮箱账号
        smtpObj.sendmail(self.Sender_mail, self.Receive_mail, message.as_string())
        smtpObj.quit()
        print('邮箱发送成功')

    # 启动
    def run(self):
        Subject = self.Subject                               # 标题
        self.get_time()                                      # 获取现在日期
        Time_now = self.time_now                             # 时间
        City = self.City                                     # 城市
        self.get_weather_air()                               # 获取天气
        Weather = self.weather                               # 天气
        Low_air = self.low_air                               # 最低温度
        High_air = self.high_air                             # 最高温度
        count_love_time = self.count_love_time()
        Days, Years, Mounts, ds = count_love_time
        self.next_verse_days()
        Verse = self.verse                                  # 周年纪念日
        G_name = self.Attn_name                             # 女孩名字
        G_days = self.next_bday_days(self.Girl_bday)        # 女孩生日倒计时
        B_name = self.Sender_name                           # 男孩名字
        B_days = self.next_bday_days(self.Boy_bday)         # 男孩生日倒计时
        Say_en, Say_ch = self.get_love_sayings()            # 每日语录
        Sign_name = self.Sender_name

        # 发送的邮件内容
        mail_msg = f'''<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>早上好</title>
</head>
<body>
<div style="border: 1px solid white; width: 400px; height: 650px; margin: 0 auto; border-radius:5%; background-color:#9932CC;">
    <p style="color: hotpink;margin-top: 30px; margin-left: 15px;">{Subject}</p>
    <p style="color: #00FA9A;margin: 15px">{Time_now}</p>
    <p style="margin: 15px">城市: <span style="color: #FFA500">{City}</span></p>
    <p style="margin: 15px">天气: <span style="color: dodgerblue">{Weather}</span></p>
    <p style="margin: 15px">最低气温: <span style="color: lime">{Low_air}</span></p>
    <p style="margin: 15px">最高气温: <span style="color: orangered">{High_air}</span></p>
    <p style="margin: 15px">今天是我们相恋的第<span style="color:#00BFFF">{Days}</span>天</p>
    <p style="margin: 15px">我们已经在一起<span style="color: hotpink">{Years}</span>年<span style="color: hotpink">{Mounts}</span>个月<span style="color: hotpink">{ds}</span>天</p>
    <p style="margin: 15px">距离下一个周年纪念日还有<span style="color: greenyellow">{Verse}</span>天</p>
    <p style="margin: 15px">距离<span style="color: gold">{G_name}</span>的生日还有<span style="color: yellow">{G_days}</span>天</p>
    <p style="margin: 15px">距离<span style="color: orange">{B_name}</span>的生日还有<span style="color: turquoise">{B_days}</span>天</p>
    <p style="margin-top: 30px; margin-left: 15px; margin-bottom:7px; color: #27ff28; font-size: 15px">{Say_en}</p>
    <p style="margin-top: 0; margin-left: 15px; color: #27ff28;font-size: 15px">{Say_ch}</p>
    <p style="margin-top: 50px; margin-left: 290px;color: aqua">——{Sign_name}</p>
</div>
</body>
</html>'''

        # 发送
        self.send_mail(mail_msg)

if __name__ == '__main__':
    with open('config.txt', 'r', encoding='utf-8') as f:
        read_result = f.readlines()
    for result in read_result:
        if 'Send_time' in result:
            Send_time = eval(result.split(' = ')[1].replace('\n', ''))

            while True:
                time_now = time.strftime("%H-%M", time.localtime())
                print(time_now)
                if time_now == Send_time:
                    LM = love_mail()
                    LM.run()
                    print('*'*100)
                    time.sleep(60)

5-运行效果

在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值