Skip to content

Instantly share code, notes, and snippets.

@garywill
Last active January 9, 2025 14:55
Show Gist options
  • Save garywill/cea9c61aaa8ddfc39d01daae2ba5b9e8 to your computer and use it in GitHub Desktop.
Save garywill/cea9c61aaa8ddfc39d01daae2ba5b9e8 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# usage:
# env mail_acc="[email protected]" env mail_pswd="xxx" env mail_title="Hi~" env mail_content="Hello~" smtp2self
import sys
import os
import logging
logging.basicConfig(level=logging.DEBUG)
import smtplib
from email.mime.text import MIMEText
def smtp_login(MAILADDR,PASSWORD,MAILTITLE='',MAILCONTENT=''):
smtpUA = "Mutt/%s (%s)\n" % ("1.10.1", "2018-07-13") #NOTE 更新?
smtp_servers = {
# 具体服务器表
"yandex.com": ["smtp.yandex.com",""],
"yandex.ru": ["smtp.yandex.ru",""],
"yahoo.com": ["smtp.mail.yahoo.com",""],
"gmx.com": ["mail.gmx.com",""],
"gmail.com": ["smtp.googlemail.com",""],
"zoho.com": ["smtp.zoho.com",""],
"disroot.org": ["disroot.org",""],
"163.com": ["smtp.163.com",""],
"qq.com": ["smtp.qq.com",""],
}
log = logging.getLogger(MAILADDR)
SMTPserver = smtp_servers[MAILADDR.split('@')[1]][0]
sender = MAILADDR
destination = [MAILADDR]
msg = MIMEText(MAILCONTENT, 'plain') # plain, html, xml
msg['Subject']= MAILTITLE
msg['From'] = sender
msg['User-Agent'] = smtpUA
log.debug("Connecting to smtp ...")
if smtp_servers[MAILADDR.split('@')[1]][1]=="starttls":
use_starttls = True
from smtplib import SMTP
port = 587
else:
use_starttls = False
from smtplib import SMTP_SSL as SMTP
port = 465
try:
conn = SMTP(SMTPserver,port)
except Exception as e:
log.error("Connecting fail!: %s" % (e))
try:
conn.quit()
except :
pass
return False
#conn.set_debuglevel(True)
if use_starttls:
try:
conn.starttls()
except Exception as e:
log.error("STARTTLS failed!")
return False
conn.ehlo()
log.debug("Logging in smtp ...")
try:
conn.login(MAILADDR, PASSWORD)
conn.sendmail(sender, destination, msg.as_string())
except Exception as e:
log.error("Sending smtp fail!: %s" % (e))
return False
else:
log.debug("Sending smtp to self succeeded")
return True
finally:
try:
conn.quit()
except :
pass
title = os.getenv('mail_title') if os.getenv('mail_title') else 'mail title'
content = os.getenv('mail_content') if os.getenv('mail_content') else'mail content'
if smtp_login(os.getenv('mail_acc'),os.getenv('mail_pswd'),title,content):
exit(0)
else:
exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment