Perl, Sendgrid and Net::SMTP and MIME::Entity

425 Views Asked by At

In my Perl code, I was using Net::SMTP and MIME:Entity to send email through my Sendgrid account (from their v2 api, where I could use my account login as the api)...

it was working flawlessly.

But we moved servers to a newer version. Still Unix (Linux), but has newer hardware, including a newer version of Plesk. The IP addresses are all the same, we moved them to the new hardware. We did change the IP address that is the primary one, but we made sure we added it to sendgrid whitelabel...

So I'm clueless why it would stop working. I am not getting any errors in the code, the api is connecting. But I don't ever see any emails, no matter what I do.

Since no errors, not sure why it does not work.

Here is my code, do you see the flaw that would make it fail?

sub Send_Multi_Part_Email_MimeLite {
    my ($__to,$__cc,$__bcc,$__from,$__subject,$__html_message,$__text_message,$__importance,$__xpriority,$__x_ms_priority) = @_;
    if($__x_ms_priority && ($__x_ms_priority =~ /\|/)) {
        ($__x_ms_priority,$_attachFile,$_attachFilePath) = split /\|/, $__x_ms_priority, 3;
    }
    if($__xpriority && ($__xpriority =~ /\|/)) {
        ($__xpriority,$_unSubKey,$_mbrUn) = split /\|/, $__xpriority, 3;
    }
    if($__importance && ($__importance =~ /\|/)) {
        ($__importance,$_emailType) = split /\|/, $__importance, 2;
    }

    my $_useNewSystem = 1; # Declare new system... set to 1 to use it and not use MimeLite any longer...
    if($_useNewSystem) {
        use MIME::Entity;
        use Net::SMTP;

        my $_sendIp = $ENV{REMOTE_ADDR} || "127.0.0.1";
        if($__to && ($__to =~ /\;/)) {
            $__to =~ s/\;/\,/g;
        }
        if($__cc && ($__cc=~ /\;/)) {
            $__cc =~ s/\;/\,/g;
        }
        if(!$__bcc) {
            $__bcc = '[email protected]'; # not real, but when in production is a real email, so we can get emails to confirm they are being delivered... only when debugging... Commented out if not in test mode...
        }

        if($__bcc && ($__bcc =~ /\;/)) {
            $_bcc =~ s/\;/\,/g;
        }
        if(!$__html_message) {
            $__html_message = $__text_message;
            $__html_message =~ s/\n/br()."\n"/eg;
            $__html_message =~ s/\cM\cJ/br()."\n"/eg;
        }

        $_emailSentType = "";


        $mime = MIME::Entity->build(Type  => 'multipart/alternative',
                                Encoding => '-SUGGEST',
                                From => $__from,
                                To => $__to,
                                Subject => $__subject,
                                'Importance'    => $__importance,
                                "X-Mailer"      => "$_co_domain Sendgrid Mailer - Version 2.0",
                                'X-Organization' => "$_co_name",
                                "X-Mail-Sent-For" => "The Club or www.$_co_domain/$_un; From IP: $_sendIp",
                                'X-Priority' => $__xpriority,
                                'X-MSMail-Priority' => $__x_ms_priority
        );

        $_sendKey = ""; # removed for security...

        $_removeLink = qq~https://www.testing.com/backoffice.cgi?page=unsubscribe$_sendKey~;
        $__text_message .= qq~

    You are receiving this email as a club member of The $_co_name. You can turn off your
    email subscription by logging into your back office with your username and password
    that you registered with. Or you may click:
    $_removeLink to remove yourself.
    ~;


        if($__html_message) {
            $__html_message .= qq~<br>
            <br>
    <span style="font-size: 12px; color: #808040;">
    You are receiving this email as a club member of The $_co_name.<br>
    You can turn off your email subscription by logging into your back office<br>
    with your username and password that you registered with.<br>
    Or you may click: <a href="$_removeLink">Here</a> to remove yourself,<br>
    or call our Customer Care Center at (888)123-4567 for assistance<br>
    <br>
    <br></span>
    <br>
    ~;

        }

    $mime->attach(Type => 'text/plain',
                 Encoding =>'-SUGGEST',
                 Data => $__text_message);

    $mime->attach(Type => 'text/html',
                 Encoding =>'-SUGGEST',
                 Data => $__html_message);

        if($_attachFile) {
        ### Attach stuff to it:
        if($_attachFilePath && ($_attachFilePath =~ /csv$/i)) {
            $_mimType = "text/csv";
            $_mimEncoding = "US-ASCII";
        } elsif($_attachFilePath && ($_attachFilePath =~ /gif$/i)) {
            $_mimType = "image/gif";
            $_mimEncoding = "base64";
        } elsif($_attachFilePath && ($_attachFilePath =~ /jpg$/i)) {
            $_mimType = "images/jpeg";
            $_mimEncoding = "base64";
        } elsif($_attachFilePath && ($_attachFilePath =~ /png$/i)) {
            $_mimType = "images/png";
            $_mimEncoding = "base64";
        } else {
            $_mimType = "text/plain";
            $_mimEncoding = "UTF-8";
        }
        # Attach the file that it sent...
        $mime->attach(Path     => $_attachFilePath,
                     Type     => "$_mimType",
                 Encoding => "$_mimEncoding");
      }


        # Sendgrid Login credentials
        $username = 'myloginemail';
        $password = "myloginpass";

        # Open a connection to the SendGrid mail server
        $smtp = Net::SMTP->new('smtp.sendgrid.net',
                                    Port=> 587,
                                    Timeout => 60,
                                    Hello => "testing.com", Debug => 1) or return("0","could not establish connection!: $!");

        # Authenticate
        if($smtp) {
            $smtp->auth($username, $password);
            # Send the rest of the SMTP stuff to the server
            $smtp->mail($__from);
            $smtp->to($__to);
            $smtp->data($mime->stringify);
            $smtp->quit();

            open(DEB,">>/home/path/files/aa_mime_email_debug_tracking.txt");
            seek(DEB,0,2);
            $_resultMsg = $smtp->message();
            $_resultMsg =~ s/\n//eg;
            $_resultMsg =~ s/\cM\cJ//eg;


            # just added this, not sure if it will work... want to create a loop of the $smtp to put it in the debug file, so I can see what is happening and why email does not go anywhere, but connection works...
            $_resultMsg2 = "";
              foreach (keys %{$smtp}) {
                $_resultMsg2 .= "," if $_resultMsg2;
                # Test this one:
              $_resultMsg2 .= " $_ => ${$hash_ref}{$_}";
              # Then test this one:
              $_resultMsg2 .= ", $_ = " . ${$hash_ref}->{$_};
            }

            print DEB qq~Result: '~ . $_resultMsg . qq~'; smtpTest: '~ . $_resultMsg2 . qq~'; From => "$__from", To => "$__to", Subject => "$__subject", If Member Username passed: "$_mbrUn", on: ~ . Format_Date_For_Viewing(time(),"") . "\n";
            close(DEB);
            return (1,"");
        } else {

            open(DEB,">>/home/path/files/aa_mime_email_debug_tracking.txt");
            seek(DEB,0,2);
            print DEB qq~ERROR: '~ . $smtp->message() . qq~' (Sendgrid error!!!) - From => "$__from", To => "$__to", Subject => "$__subject", If Member Username passed: "$_mbrUn", on: ~ . Format_Date_For_Viewing(time(),"") . "\n";
            close(DEB);
            return (0,$smtp->message());
        }
    } else {
        # Code for old email system... not using sendgrid, using sendmail... no longer in use, but code left there for times when sendgrid not working or something... used MimeLite
    }
}

Anyhow, I have no idea why it is not working. The Server admins checked and there are no errors or no emails in the queue, either... so nothing just stuck somewhere, that we can find...

Can someone see anything, aside from my terrible programming??? lol

Thanks, -Richard

1

There are 1 best solutions below

0
On

If the program worked before, did not change, and is not giving any errors, there is probably nothing wrong with it. Test sending the email manually.

Start by encoding your username and password:

perl -MMIME::Base64 -e 'print encode_base64 $_ for qw/myloginemail myloginpass/'

Then use telnet with encoded username after the first 334 and password after the second:

telnet smtp.sendgrid.net 587
Trying 167.89.118.51...
Connected to smtp.sendgrid.net.
Escape character is '^]'.
220 SG ESMTP service ready at ismtpd0011p1las1.sendgrid.net
helo testing.com
250 Hello, nice to meet you
auth login
334 VXNlcm5hbWU6
bXlsb2dpbmVtYWls
334 UGFzc3dvcmQ6
bXlsb2dpbnBhc3M=
235 Authentication succeeded
mail from:<[email protected]>
250 2.1.5 Ok
rcpt to:<[email protected]>
250 2.1.5 Ok
data
354 End data with <CR><LF>.<CR><LF>
subject: test

This is test 0.
.
250 2.0.0 Ok: queued as BBAEA3483C73
quit
221 2.0.0 Bye
Connection closed by foreign host.