Skip to content

Instantly share code, notes, and snippets.

@Alfex4936
Created January 9, 2021 09:23
Show Gist options
  • Save Alfex4936/9e8c7101df707d2b2d0f41645dbc37db to your computer and use it in GitHub Desktop.
Save Alfex4936/9e8c7101df707d2b2d0f41645dbc37db to your computer and use it in GitHub Desktop.
Python smptlib example (HTML + img)
import smtplib
import time
from datetime import datetime
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import requests
from bs4 import BeautifulSoup
from pytz import timezone
FROM = "[email protected]"
TO = "[email protected]"
PSWD = "password"
URL = "http://prod.danawa.com/info/?pcode=10129599&cate=112787"
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 9.10; rv:69.0) Gecko/20100101 Firefox/68.0"
}
def getPrice(url=URL) -> str:
result = None
try:
result = requests.get(URL, headers=headers)
result.raise_for_status()
except requests.exceptions.HTTPError as http:
print("HTTP Error:", http)
except requests.exceptions.ConnectionError as conn:
print("Connection Error:", conn)
except requests.exceptions.Timeout as tm:
print("Timeout Error:", tm)
except requests.exceptions.RequestException as err:
print("Something wrong:", err)
assert result is not None
soup = BeautifulSoup(result.content, "html.parser", from_encoding="iso-8859-1")
price = soup.select_one("a.lwst_prc > em.prc_c")
return price.text
def sendMail(mail=FROM, password=PSWD):
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(FROM, PSWD)
prd = "Razer Basilisk Ultimate"
now = datetime.now(timezone("Asia/Seoul"))
nowPrice = f"오늘 {prd} 가격: {getPrice()}원"
subject = now.strftime("[%y/%m/%d] ")
msg = MIMEMultipart("related")
msg["Subject"] = subject + nowPrice # [21/01/09] 오늘 ~ 가격: ~원
msg["From"] = FROM # 발신
msg["to"] = TO # 수신
html = f"""\
<html>
<head></head>
<body>
<img src="cid:image1" alt="Logo" style="width:800px;height:590px;"><br>
<p><h1 style="text-align: center;font-size:20px;"><a href="{URL}" target="_blank" rel="noopener">{prd}</a></h1></p>
</body>
</html>
"""
imgSrc = MIMEText(html, "html")
msg.attach(imgSrc)
with open("basil.png", "rb") as img:
msgImg = MIMEImage(img.read())
msgImg.add_header("Content-ID", "<image1>")
msg.attach(msgImg)
server.sendmail(FROM, TO, msg.as_string())
server.quit()
if __name__ == "__main__":
while True:
sendMail()
time.sleep(60 * 60 * 24)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment