用 Python 写了个小工具:轮询收件箱,如果收到的邮件满足某个条件,则向 IFTTT 发送触发邮件。
目前运行在树莓派上,但是办公室有时候会断电。现在想找个可靠又低成本的服务来运行这个代码。我听有些服务器会疯掉邮件发送端口。想请问各位老哥,哪家服务比较好呢?
import time
import email
import imaplib
import smtplib, ssl
from email.mime.text import MIMEText
import base64
import os
from os.path import join, dirname
from dotenv import load_dotenv
dotenv_path = join(dirname(__file__), ".env")
load_dotenv(dotenv_path)
PASSWORD = os.environ["EMAIL_PASSWORD"]
def fire_in_the_hole():
smtp_server = 'smtp.gmail.com'
port = 465
from_addr = 'sender@gmail.com'
to_addrs = ['trigger@applet.ifttt.com']
message = MIMEText('Hey big brother!')
message['subject'] = 'Alert received'
message['from'] = from_addr
message['to'] = ', '.join(to_addrs)
# we'll connect using SSL
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(from_addr, PASSWORD)
server.sendmail(from_addr, to_addrs, message.as_string())
def check_email():
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('sender@gmail.com', PASSWORD)
mail.select('inbox')
status, data = mail.search(None, 'UNSEEN', 'FROM "no-reply@example.com"')
mail_ids = []
for block in data:
mail_ids += block.split()
if not mail_ids:
return
for i in mail_ids:
status, data = mail.fetch(i, '(RFC822)')
for response_part in data:
if isinstance(response_part, tuple):
message = email.message_from_bytes(response_part[1])
if message.is_multipart():
mail_content = ''
for part in message.get_payload():
mail_content += part.get_payload()
else:
mail_content = message.get_payload()
mail_content = base64.b64decode(mail_content).decode('utf-8')
if 'dropped' in mail_content:
fire_in_the_hole()
def task():
while True:
check_email()
time.sleep(300)
if __name__ == "__main__":
task()
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.