Skip to content

Instantly share code, notes, and snippets.

@jfstenuit
Created March 20, 2024 16:14
Show Gist options
  • Save jfstenuit/79d20999530788fa58e064148b36c02b to your computer and use it in GitHub Desktop.
Save jfstenuit/79d20999530788fa58e064148b36c02b to your computer and use it in GitHub Desktop.
Test MS365 SASL authenticated SMTP sending from linux

In order to troubleshoot the low-level communication of sending e-mail through Exchange Online using SASL authenticated SMTP, you can user this script :

#!/usr/bin/perl

use strict;
use warnings;
use Net::SMTP;
use Authen::SASL;

# Recipient email
my $recipient = shift(@ARGV);

unless (defined($recipient) && ($recipient =~ /^[A-Z0-9_+]+([A-Z0-9_+.)*@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}$/i)) {
        print STDERR "Usage: $0 email\@domain.tld\n";
        exit 1;
}

my ($server,$username,$password);

open(F,"</etc/postfix/sasl_passwd") or die "Cannot open /etc/postfix/sasl_passwd : $!";
while(<F>) {
        if (/^(\S+)\s+([^:]+):(\S+)/) {
                ($server,$username,$password)=($1,$2,$3);
        }
}
close(F);


# Create SMTP client
my $smtp = Net::SMTP->new(
    'smtp.office365.com',
    Port    => 587,
    Timeout => 30,
    Debug   => 1,  # Set to 0 to disable debugging output
);

die "Could not connect to server: $!" unless $smtp;

# Upgrade connection to TLS
$smtp->starttls(SSL_verify_mode => 0)
    or die "Failed to start TLS: $!";

# Authenticate
$smtp->auth($username, $password)
    or die "Failed to authenticate: $!";

# Send email
$smtp->mail($username);
$smtp->to($recipient);
$smtp->data();
$smtp->datasend("To: $recipient\n");
$smtp->datasend("From: $username\n");
$smtp->datasend("Subject: Test Email\n");
$smtp->datasend("\n");
$smtp->datasend("This is a test email sent via Perl script using STARTTLS.\n");
$smtp->dataend();

# Close the connection
$smtp->quit;

print "Email sent successfully!\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment