6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PythonでメールアドレスからMXレコードを引いて直接メールを送信する

Last updated at Posted at 2015-05-01

概要

メールサーバーの指定をしなくてもいいプログラムを作ってみたかったので書いてみました。

最初にMXレコードを引くためのモジュールを入れます。

pip install dnspython

実行

引数に宛先と差出人のメールアドレスを渡す。

python sendmail.py to@example.com from@example.com

実装

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はスパム対策なのか、なんらかの制限をかけているようで、送信すると下記のようなエラーが出る可能性があります。

smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [Errno 54] Connection reset by peer
6
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?