【问题标题】:How do i implement an exception for my "Send Mail" script? (Using "Mail" Gem)如何为我的“发送邮件”脚本实现异常? (使用“邮件”宝石)
【发布时间】:2012-02-04 04:53:53
【问题描述】:

我用基本的 Ruby 编写了一个 SendMail 脚本,它运行良好。问题是如果脚本发送到像“notavliable1”这样的电子邮件地址,我会收到无法访问收据的 SMTP 错误并且脚本停止。

我需要一个例外来过滤邮件地址或一个正则表达式。

这里是sn-p:

require 'mail'

mail = Mail.new do
      from 'peter@lustig.de'
      to ("#{send.toAdress}")
      subject ("#{send.subject}")

      html_part do
        content_type 'text/html; charset=UTF-8'
        body ("#{send.body}")
      end
    end

如何告诉我的 sn-p 跳过无效的“send.toAdress”?

我正在使用“邮件”gem。

【问题讨论】:

    标签: ruby-on-rails ruby exception gem sendmail


    【解决方案1】:

    使用异常可能是最佳实践,因为 REGEX 不会发现邮件地址中的所有可能错误。

    我不知道具体的 gem,但如果可以使用正则表达式解决方案,您可以添加

    require 'mail'
    
    mail = Mail.new do
          from 'peter@lustig.de'
          to ("#{send.toAdress}")
          subject ("#{send.subject}")
    
          html_part do
            content_type 'text/html; charset=UTF-8'
            body ("#{send.body}")
          end
        end if send.toAdress.match /regex_to_match_email/
    

    至于/regex_to_match_email/,我认为这是一个品味问题。我一般用这个

    \b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b
    

    然而,它远非完美。

    【讨论】:

    • 谢谢你,但我想我需要一个例外。该脚本需要运行很多时间而不会出错。
    猜你喜欢
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 2016-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多