I wanted to make a program that doesn't require specifying a mail server, so I wrote it.
First, insert the module for pulling MX records.
pip install dnspython
Pass the recipient and sender's email address as 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()
It seems that Gmail has some restrictions on anti-spam measures, and if you send it, you may get the following error.
smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [Errno 54] Connection reset by peer
Recommended Posts