Perl code to email files using Gmail SMTP

I’m developing a Perl program that needs to send emails with file attachments using Gmail’s SMTP service. I’ve tried several methods but haven’t succeeded yet.

Here’s my current code attempt:

use Email::Sender::Simple qw(sendmail);
use Email::Sender::Transport::SMTP::TLS;
use Email::MIME;
use File::Slurp;

my $transport = Email::Sender::Transport::SMTP::TLS->new({
    host => 'smtp.gmail.com',
    port => 587,
    username => '[email protected]',
    password => 'mypassword',
});

my @logData = read_file("$logPath");
my $message = Email::MIME->create(
    header_str => [
        From => '[email protected]',
        To => "$recipientEmail",
        Subject => "Log report for $serverName",
    ],
    body_str => "@logData",
);

sendmail($message, { transport => $transport });

The email goes through, but I need guidance on how to properly include file attachments when emailing through Gmail in Perl.

Your Email::MIME construction is the problem. I ran into the same Gmail attachment issues and had to completely restructure the message object. Don’t use body_str - build a multipart message instead where each attachment becomes its own MIME part. Keep using File::Slurp to read your file, but then create the message with a parts array. Put your main body as the first element, then add each attachment as additional parts with proper content type headers. For your log file, use content_type => ‘text/plain’ and add disposition => ‘attachment’ with the filename parameter. Most file types need base64 encoding. Also check your Gmail auth - standard passwords don’t work anymore. You need app passwords enabled in your Google account security settings.

You’re creating a basic Email::MIME object but need multipart structure for attachments. Had this same issue last year. Don’t use body_str directly. Build it with a parts array instead - first part is your text content, second part is the attachment. Set path => ‘your_file_path’, content_type => ‘application/octet-stream’ (or whatever fits), and don’t forget the filename attribute. Also check your Gmail auth. Regular passwords won’t work anymore - you need an app-specific password from your Google account settings.

youre missing the attachment part - you need to create a multipart message instead of just body_str. try using Email::MIME->create with parts => […] and include your file as a separate part with encoding => ‘base64’ for binary files. also make sure youre using an app password, not your regular gmail password since they changed that.