LoginSignup
2
1

More than 3 years have passed since last update.

Pythonのsmtplibでメールを送信せずにSMTPのMAIL FROMコマンド、RCPT TOコマンドだけ使いたい

Last updated at Posted at 2020-01-19

結論


import smtplib

server = smtplib.SMTP('gmail-smtp-in.l.google.com.', 25) # 接続先サーバー, ポート番号
server.ehlo()
server.mail('example@example.com') # MAIL FROMに指定するアドレス
server.rcpt('example@gmail.com') # RCPT TOに指定するアドレス

~

のような感じで smtplib.SMTP.mail()smtplib.SMTP.rcpt() を使えば良さそう。

詳細

smtplib.SMTP.mail()、 smtplib.SMTP.rcpt() を使えば良いらしいが……

スクリーンショット 2020-01-19 11.01.22.png

smtplibのドキュメント↑には、SMTPの MAIL FROMRCPT TO コマンドを使いたかったら mail() メソッド、 rcpt() メソッドを使えば良いよ〜〜と書いてある↑。
しかし、引数にどんな値を渡せば良いのかなど mail(), rcpt() メソッドの詳細が書かれていない。

smtplib --- SMTP プロトコルクライアント — Python 3.8.1 ドキュメント
https://docs.python.org/ja/3/library/smtplib.html

inspect.getsource() で実装を見る

import inspect
import smtplib

mail = inspect.getsource(smtplib.SMTP.mail)
rcpt = inspect.getsource(smtplib.SMTP.rcpt)

のような感じで smtplib.SMTP.mail()、smtplib.SMTP.rcpt() のソースコード文字列を取得する。

こんな実装らしい↓
標準ライブラリがPEP8無視してるのはちょっと面白い。
(mail() の x.lower()=='smtputf8' の部分。E225: missing whitespace around operator)

smtplib.SMTP.mail()
    def mail(self, sender, options=()):
        """SMTP 'mail' command -- begins mail xfer session.

        This method may raise the following exceptions:

         SMTPNotSupportedError  The options parameter includes 'SMTPUTF8'
                                but the SMTPUTF8 extension is not supported by
                                the server.
        """
        optionlist = ''
        if options and self.does_esmtp:
            if any(x.lower()=='smtputf8' for x in options):
                if self.has_extn('smtputf8'):
                    self.command_encoding = 'utf-8'
                else:
                    raise SMTPNotSupportedError(
                        'SMTPUTF8 not supported by server')
            optionlist = ' ' + ' '.join(options)
        self.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender), optionlist))
        return self.getreply()

smtplib.SMTP.rcpt()
    def rcpt(self, recip, options=()):
        """SMTP 'rcpt' command -- indicates 1 recipient for this mail."""
        optionlist = ''
        if options and self.does_esmtp:
            optionlist = ' ' + ' '.join(options)
        self.putcmd("rcpt", "TO:%s%s" % (quoteaddr(recip), optionlist))
        return self.getreply()

というわけで、mail()rcpt() の引数には、それぞれ単純に指定したいメールアドレス文字列を渡せば良いっぽい (冒頭に戻る)。

2
1
0

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
2
1