qt mail scripts > 기타 Others

본문 바로가기

기타 Others

qt mail scripts

페이지 정보

작성자 Author 관리자1 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 작성일 Date26-02-27 20:00 조회 Read32회 댓글 Reply0건

본문

import os

import sys

import re

from datetime import datetime, timedelta

import requests

from bs4 import BeautifulSoup

import smtplib

from email.mime.text import MIMEText

 

# Email Config

SMTP_HOST = "smtp.gmail.com"

SMTP_PORT = 587

SMTP_USER = "jaejongbaek@gmail.com"

SMTP_PASS = "tkmwyphqpdpmjfle"

MAIL_FROM = "jaejongbaek@gmail.com"

MAIL_TO = ["jjbaek35@gmail.com"]  # 수신자 목록

 

UA = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36"}

TIMEOUT = 15

 

def fetch_source_1(selected_date: str):

    url = "https://sum.su.or.kr:8888/bible/today"

    output = []

    try:

        resp = requests.get(url, headers=UA, timeout=TIMEOUT)

        resp.raise_for_status()

    except Exception as e:

        output.append(f"[Source 1] Request error: {e}\n")

        return output

 

    soup = BeautifulSoup(resp.text, "html.parser")

    try:

        script_tag = soup.find("script", string=re.compile(r'\$\("#base_de"\)\.val\("\d{4}-\d{2}-\d{2}"\);'))

        date_match = re.search(r'\$\("#base_de"\)\.val\("(\d{4}-\d{2}-\d{2})"\);', script_tag.string if script_tag else "")

        date_text = date_match.group(1) if date_match else "Date not found"

        output.append(f"{date_text}\n")

    except Exception:

        output.append("Source 1 Date not found.\n")

 

    title_div = soup.find("div", class_="bible_text")

    output.append(f"{title_div.get_text(strip=True)}\n" if title_div else "Title not found.\n")

 

    info_div = soup.find("div", class_="bibleinfo_box")

    output.append(f"{info_div.get_text(strip=True)}\n" if info_div else "Bible Info not found.\n")

 

    verses_ul = soup.find("ul", class_="body_list")

    if verses_ul:

        for li in verses_ul.find_all("li"):

            num = li.find("div", class_="num")

            txt = li.find("div", class_="info")

            if num and txt:

                output.append(f"{num.get_text(strip=True)} {txt.get_text(strip=True)}\n")

    else:

        output.append("Bible Verses not found.\n")

 

    body_content = soup.find("div", class_="body_cont")

    if body_content:

        b_text = body_content.find("div", class_="b_text")

        if b_text:

            output.append(f"\n요약: {b_text.get_text(strip=True)}\n")

        for section in body_content.find_all("div", class_=lambda c: c in {"g_text", "text"} if c else False):

            output.append("\n" + section.get_text(strip=True) + "\n")

    else:

        output.append("Commentary content not found.\n")

 

    return output

 

def fetch_source_2(selected_date: str):

    url_en = f"http://qt.swim.org/user_utf/dailybibleeng/user_print_web.php?edit_all={selected_date}"

    output = []

    try:

        resp = requests.get(url_en, headers=UA, timeout=TIMEOUT)

        resp.raise_for_status()

        soup_en = BeautifulSoup(resp.text, "html.parser")

        output.append("\n")

        for td in soup_en.find_all("td", {"class": "padding"}):

            text = td.get_text(strip=True)

            if text:

                output.append(text + "\n\n")

    except Exception as e:

        output.append(f"[Source 2] Request error: {e}\n")

    return output

 

def compute_target_date(arg: str | None) -> str:

    if arg:

        try:

            datetime.strptime(arg, "%Y-%m-%d")

            return arg

        except ValueError:

            print(f"[Warn] Invalid date '{arg}', expected YYYY-MM-DD. Falling back to tomorrow.")

    return (datetime.today() + timedelta(days=1)).strftime("%Y-%m-%d")

 

def send_email(subject: str, body: str):

    msg = MIMEText(body, _charset="utf-8")

    msg["Subject"] = subject

    msg["From"] = MAIL_FROM

    msg["To"] = ", ".join(MAIL_TO)

 

    with smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=30) as s:

        s.starttls()

        s.login(SMTP_USER, SMTP_PASS)

        s.sendmail(MAIL_FROM, MAIL_TO, msg.as_string())

 

    print("[OK] Email sent.")

 

def main():

    selected_date = compute_target_date(sys.argv[1] if len(sys.argv) > 1 else None)

    print(f"Fetching content for {selected_date}...\n")

 

    content_1 = fetch_source_1(selected_date)

    content_2 = fetch_source_2(selected_date)

 

    combined = ["\n📖 성경 묵상 / Daily Bible Reading\n\n"] + content_1 + ["\n"] + content_2

    email_body = "".join(combined)

 

    subject = f"📬 Daily Bible Reading – {selected_date}"

    send_email(subject, email_body)

 

if __name__ == "__main__":

    main()


  • 페이스북으로 보내기
  • 트위터로 보내기
  • 구글플러스로 보내기

댓글목록 Reply List

등록된 댓글이 없습니다. No posts



Southern Baptist Convention Arizona Global Baptist Church
536 E. Fillmore St., Tempe, AZ 85288 / T. (480) 442-7329

PC 버전으로 보기