【问题标题】:Debugging Email::Sender::Simple with Email::Sender::Transport::SMTPS使用 Email::Sender::Transport::SMTPS 调试 Email::Sender::Simple
【发布时间】:2018-05-13 18:16:20
【问题描述】:

我正在编写一个电子邮件服务,它使用Email::Sender::SimpleEmail::Sender::Transport::SMTPS 向我的用户发送数据。现在,我有一个包,它应该只接受一些输入并发送电子邮件:

package MyApp::Service::Mail;

use Email::Sender::Simple qw(sendmail);
use Email::Simple;
use Email::Sender::Transport::SMTPS;
use Try::Tiny;
use Dancer;

use constant CANT_SEND_MAIL    => -1;
use constant SENT_SUCCESSFULLY => 1;

sub new {
    my $class   = shift;
    my $self    = {};

    bless  $self, $class;
    return $self;
}

sub sendEmail {
    my $self    = shift;
    my $to      = shift;
    my $subject = shift;
    my $body    = shift;
    my $failed  = 0;

    my $email = Email::Simple->create(
        header => [
            To      => $to,
            From    => 'noreply@myapp.com',
            Subject => $subject
        ],
        body => $body
    );

    my $transport = Email::Sender::Transport::SMTPS->new({
        host          => config->{smtp_host},
        port          => config->{smtp_port},
        sasl_username => config->{smtp_username},
        sasl_password => config->{smtp_password},
        ssl           => 'ssl'
    });

    try {
        sendmail($email, {transport => $transport});
    } catch {
        $failed = 1;
    }

    return $self->CANT_SEND_MAIL if ($failed eq 1);
    return $self->SENT_SUCCESSFULLY;
}

1;

这在很大程度上基于example from the CPAN page for the modules involved

请注意,这些配置变量来自Dancers config.yml,并且我已确认它们已正确传递。我还确认$to$body$subject 包含我所期望的内容。

正在调用 sendEmail 函数并返回 1 (SENT_SUCCESSFULLY),但我在电子邮件客户端的“已发送”框中看不到任何内容,接收地址也没有任何内容。我一直在尝试寻找某种调试功能来深入研究失败的原因,但无济于事。

调用它的代码是:

package MyApp::Service::Mail::User;

use MyApp::Service::Mail;
our @ISA = qw(MyApp::Service::Mail);

sub sendPasswordByEmail {
    my $self     = shift;
    my $to       = shift;
    my $username = shift;

    my $subject = "Test E-Mail";

    (my $body = << "    END_MESSAGE") =~ s/^ {4}//gm;
    Dear $username,

    This is a test e-mail.
    END_MESSAGE

    return $self->sendEmail($to, $subject, $body);
}

1;

我可以确认 SMTP 帐户在我的电子邮件客户端 (Thunderbird) 中使用时确实有效。关于为什么这个函数可能返回 1 而没有成功的任何建议?有没有办法调试这个和我的 SMTP 服务器之间的连接(它是第 3 方,所以无法检查日志),以查看是否正在建立连接以及正在传递什么/是否有问题?

【问题讨论】:

  • 在修复了 Haarg 建议的 try/catch 错误后,最好看看实际抛出的错误。
  • @stevenl 没有错误,它正常工作。

标签: perl smtp dancer


【解决方案1】:

try {} catch {} 块后缺少一个分号。没有它,以下行将成为同一语句的一部分,因此整个 try/catch 块是基于 $failed 的条件,此时它永远不会是 1。

这是Try::Tiny 实现的不幸副作用,但在纯perl 实现中无法避免。您现有的代码被解析如下:

try(
    sub {
        sendmail($email, {transport => $transport});
    },
    catch(
        sub {
            $failed = 1;
        },
        return($self->CANT_SEND_MAIL),
    ),
) if ($failed eq 1);

【讨论】:

  • 作品,周二赏金。
猜你喜欢
  • 1970-01-01
  • 2015-08-24
  • 2015-06-05
  • 1970-01-01
  • 2012-11-23
  • 1970-01-01
  • 1970-01-01
  • 2012-12-28
  • 2016-02-06
相关资源
最近更新 更多