Regular love message to girlfriend Daily Mail

I want to make a small gift for my girlfriend

A few days ago is Valentine's day. It's too vulgar to send dolls. I want to use my knowledge. After all, I'm still half a programmer. Customize a daily email for my girlfriend. Learning materials for programming: Click to get them for free

Decomposition task

Let's break down the task. We need to:

  • Send mail
  • Daily Sentence source
  • Scheduled task
  • programming
  • Customized service

Send mail

I use the simplest Python Programming and use SMTP to send e-mail. The e-mail has three elements: host e-mail server address, user your e-mail account, password your e-mail password. OK, give our sample code. The following is because I want to pay attention to a little and encapsulate it

import smtplib

from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.header import Header
receivers = ['Your email@qq.com']

def send_email(message,receivers=receivers):
    # Third party SMTP service
    mail_host = "smtp.163.com"  # Set up server
    mail_user = "Your email@163.com"  # user name
    mail_pass = "It's from Netease mailbox token"  # Password
    sender = mail_user
    # receivers = ['receive@qq.com']  # To receive email, you can set it as your QQ email or other email
    try:
        smtpObj = SMTP_SSL(mail_host,465)//465,25 will do. Explain why I use it later
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(mail_user, receivers, message.as_string())
        print("Mail sent successfully")
    except smtplib.SMTPException:
        print("Error: Unable to send mail")
Copy code

At present, we can complete the first step of sending email, but what about our email content? We can't write it every day A few days ago, I learned some reptile fur from teacher Cui Qingcai's book Create a new Python file and set a get_info method, we use crawlers to get our daily sentence I found a daily sentence on this website. Of course, you can find daily love words, rainbow fart, etc Let me use the daily sentence as an example

When we examine the elements directly, we can see

The content we want is hidden under the < H5 > tag and class=e. we are lazy and use lxml to deal with it

result = html.xpath('//h5[@class="e"]/a/text()')[0]
Copy code

In this way, we can get the value we want and how to translate it. Do it again in the same way:

result_translate = html.xpath("//div[@class='fl dailyEtext']/h5[2]/text()")[0]
Copy code

The code for obtaining the whole daily sentence is as follows:

import requests
from lxml import etree
def get_everyday_sentence():
    # A sentence of Hujiang English every day
    URL = "http://news.iciba.com/index.php?mod=dailysentence"
    r = requests.get(URL)
    html = etree.HTML(r.text)
    result = html.xpath('//h5[@class="e"]/a/text()')[0]
    result_translate = html.xpath("//div[@class='fl dailyEtext']/h5[2]/text()")[0]
    # print(result, result_translate)
    return result, result_translate
 Copy code

Solution of timing problem

As a fake programmer, the level is not enough. I think the solution is to cycle, get the time all the time, and send e-mail at 8 o'clock every day I just write a dead cycle and ask for the time in seconds. At first, I set 500s. I feel it's a little too long. I set it every 5 seconds OK, my implementation is as follows:

import time
from SendEmailforgf import timer
from SendEmailforgf.get_info import get_everyday_sentence
from email.mime.text import MIMEText
from email.header import Header
from sendEmail import send_email
from timer import *
if __name__ == '__main__':
    while (True):
        if get_time(3) + 8 == 8:
            every_senntence_info = get_everyday_sentence()
            message = MIMEText(
                every_senntence_info[0] + every_senntence_info[1] + " " + f" It's still a few minutes before your birthday{int(timer.count_birthday())}day",
                'plain',
                'utf-8')
            message['From'] = Header("Pig man doesn't eat lollipops", 'utf-8')
            message['To'] = Header("Lovely Xiao Zhao", 'utf-8')

            subject = 'One sentence a day'
            message['Subject'] = Header(subject, 'utf-8')
            reciver = "addressee@qq.com"
            send_email(message, reciver)
            time.sleep(3600)
        else:
            print("I'm still running")
            time.sleep(5)
            # time.sleep(60*60*24)
Copy code

There are some customized methods that haven't been introduced yet. Introduce them immediately This is my main program entry

customization

I think the above daily sentence, rainbow fart, is too common. You need to add some knowledge belonging to both of you, such as her birthday, and write a method to calculate how many days her birthday is still from today:

import time
import datetime
def get_time(num):
    return time.gmtime().__getitem__(num)
def count_birthday():
    birthday_birth = '1998-07-07' # Her birthday
    current_birth = f"{get_time(0)}-07-07"
    today = datetime.datetime.today()
    if convert_time(today.strftime("%Y-%m-%d")) > convert_time(current_birth):
        day = ((convert_time(current_birth) - convert_time(
            today.strftime("%Y-%m-%d")) + 60 * 60 * 24 * 365)) / (60 * 60 * 24 )
    else:
        day = (convert_time(current_birth) - convert_time(today.strftime("%Y-%m-%d"))) / (60 * 60 * 24 )
    #print(day)
    return day
def convert_time(DATE):
    return int(time.mktime(time.strptime(DATE, "%Y-%m-%d")))
Copy code

I wrote a simple judgment. Compare today's millisecond value with this year's birthday millisecond value to see if this year's birthday has passed. At present, the date has not passed. I don't know if there will be any bug s in this place. Let's change it again

Programming implementation

In fact, the above is my programming method, but only when the code runs, can it cycle and send e-mail. My computer can't run this small program all the time. At this time, I remember my cloud server that doesn't stop. Deploying this Python code to the cloud server solves the problem that the program has no place to run

When purchasing a server and installing Python, the following table does not apply. I just said that I encountered a problem when putting my own code on it, but the module could not be found. After looking for the information, I understood that it was due to the different way of writing the path between the local computer and the server. I added a line of code to the file with the main method to solve this problem:

import sys
import os
sys.path.append(os.path.dirname(sys.path[0]))
Copy code

Just run the uploaded code on the server: nohup python3 main py &

Happy, as a half program, according to their own wishes, to achieve the functions they want to achieve. The code is very simple. I will work hard next time


① More than 3000 Python e-books
② Python development environment installation tutorial
③ Python 400 set self-study video
④ Common vocabulary of software development
⑤ Python learning Roadmap
⑥ Project source code case sharing

If you can use it, you can take it away directly. In my QQ technical exchange group (technical exchange and resource sharing, advertising is not allowed) you can take it away by yourself. The group number is 895937462.
 

Keywords: Back-end Programmer

Added by bals28mjk on Thu, 24 Feb 2022 03:54:29 +0200