Using Perl to send emails from remote server

Ok, I learned a lot working on this and I still don’t know way more than I probably should but here’s what I did and a working perl script for those who might want or need one.

The script is running on a DigitalOcean vps with Ubuntu 16.04 and sending the email from another DigitalOcean vps running MIAB. You may have to install the perl modules referenced and first I needed to add my remote domain’s IP address to POSTFIX on the MIAB server like so:

Edit this file:
sudo nano /etc/postfix/main.cf

Look for this line:
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128

Add the remote server IP like this (example IP used: 199.99.99.99):
mynetworks = 199.99.99.99 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128

Save the file then reload postfix:
sudo postfix reload

Here’s the perl script. I put mine in the “/usr/lib/cgi-bin/” directory:

#!/usr/bin/perl

use Net::SMTP;
use MIME::Base64;

# Server and User Authentication:
my $smtpserver = 'box.youremailserver.com';
my $user = 'you@yourwebsite.com';
my $password = 'your-password';

my $from ='you@yourwebsite.com';

# Test email data:
my $send_to = 'test@somewhere.com';
my $send_subj = 'Perl on MAIB Test';
my $html_msg = '<h3>This is the HTML test message</h3>';

&doMail ($send_to, $send_subj, $html_msg);

sub doMail {

	my ($to, $subj, $msg) = @_;	
	
	my $smtp = Net::SMTP->new(
		$smtpserver,
		   Timeout => 30,
		   Debug   => 0,
	);

	$smtp->datasend("AUTH LOGIN\n");
	$smtp->response();

#  -- Login to SMTP --
	# Enter sending email box address username below.
	$smtp->datasend(encode_base64($user) );
	$smtp->response();

	#  -- Enter email box address password below.   login to SMTP --
	$smtp->datasend(encode_base64($password) );
	$smtp->response();
			  
	$smtp->mail($from);

	$smtp->to($to);

	$smtp->data();

#  -- This part creates the SMTP headers you see --
	$smtp->datasend("From: $from \n");
	$smtp->datasend("To: $to \n");
	$smtp->datasend("Content-Type: text/html \n");
	$smtp->datasend("Subject: $subj");

	# then a line break to separate headers from message body
	$smtp->datasend("\n");

	# the html message:
	$smtp->datasend($msg);

	$smtp->datasend("\n");

	$smtp->dataend();
	
	if ($smtp->error) {print $smtp->error}

	else {print "Message Sent \n"}

	$smtp->quit;

	return;
}