Je voulais créer un programme qui ne nécessite pas de spécifier un serveur de messagerie, alors je l'ai écrit.
Insérez d'abord le module pour extraire les enregistrements MX.
pip install dnspython
Transmettez l'adresse e-mail du destinataire et de l'expéditeur comme arguments.
python sendmail.py [email protected] [email protected]
sendmail.py
# -*- coding: utf-8 -*-
import smtplib
from email.MIMEText import MIMEText
from email.Header import Header
from email.Utils import formatdate
import sys
import dns.resolver
if __name__ == "__main__":
argvs = sys.argv
if len(argvs) != 3:
print 'Usage arg1 = to_address, arg2 = from_address'
quit()
to_address = argvs[1]
from_address = argvs[2]
to_list = to_address.split('@')
to_address = '<' + to_address + '>'
from_address = '<' + from_address + '>'
if len(to_list) < 2:
print 'format error to_address'
quit()
domain = to_list[1]
mailserver = dns.resolver.query(domain, 'MX')
if len(mailserver) < 1:
print 'not found mx recored'
quit()
mailserver = mailserver[0].to_text().split(' ')
mailserver = mailserver[1][:-1]
print mailserver
charset = "ISO-2022-JP"
subject = u"this is Python test mail!"
text = u"this is Python test mail!"
msg = MIMEText(text.encode(charset),"plain",charset)
msg["Subject"] = Header(subject,charset)
msg["From"] = from_address
msg["To"] = to_address
msg["Date"] = formatdate(localtime=True)
smtp = smtplib.SMTP(mailserver)
smtp.sendmail(from_address,to_address,msg.as_string())
smtp.close()
Gmail semble avoir des restrictions sur l'anti-spam, et si vous l'envoyez, vous pouvez obtenir l'erreur suivante.
smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [Errno 54] Connection reset by peer
Recommended Posts