4
5

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.

net/smtpでメールアドレスが存在するか否か判定してみた

Last updated at Posted at 2017-11-09

参考にさせていただいた記事
「Ruby で メールアドレスの有効性チェックしてみた」
https://qiita.com/yutackall/items/ce9285ecdf2f03db0404

前回書いた https://qiita.com/motty93/items/43de4df4e3c5f6bb43fc
と、上の記事のハイブリッドです。

実行環境

  • OSX 10.11.6
  • Rails 5.0.4
  • Ruby 2.3.1

コード

app/controllers/concerns/mail_check.rb
require 'resolv'
require 'net/smtp'

module MailCheck
  extend ActiveSupport::Concern
  MY_DOMAIN = 'gmail.com'.freeze
  PORT = 25

  def mail_check(addr)
    domain = addr.split('@').last
    return { email: addr, domain: false, message: 'domain does not found.' } unless get_exchange(domain)

    addrs_exist?(get_exchange(domain), addr)
  rescue # 送信先メールアドレスが存在しない場合、例外処理へ
    { email: addr, domain: false, result: "#{addr} does not exist." }
  end

  private

  def get_exchange(domain)
    mx = Resolv::DNS.new.getresource(domain, Resolv::DNS::Resource::IN::MX)
    mx.exchange.to_s
  rescue
    nil
  end

  def addrs_exist?(domain, addr)
    Net::SMTP.start(domain, PORT, MY_DOMAIN) do |smtp|
      smtp.mailfrom("送信元メールアドレス")
      res = smtp.rcptto(addr).string.chomp
      { email: addr, domain: true, result: res }
    end
  end
end

telnetよりはよさそう。ただ問題が何点かあるっぽいけども。。。
使い方は前の記事を参考にしてみてください、わからんことなどあれば気軽に質問欄に。

おわり

gem化されればいいのに!

4
5
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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?