Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send an email using sendmail command?

I installed sendmail on CentOS but did not configure it and started it as daemon. Can I send an email using the sendmail command like,

sendmail [email protected] < ./myemailcontent

I have no luck with this command. It seems to connect to 127.0.0.1 then times out.

I think sendmail will connect to the remote smtp server(remotedomain.com) to deliver the email but it seems to use local smtp server to relay the email. How can I use sendmail to send an email?

like image 616
peter Avatar asked Oct 17 '25 11:10

peter


2 Answers

sendmail is "low level" tool/command to send email. It expects "raw" email.
Consider using higer level tools e.g. mail.

If you want to send simple email messages and prefer portability then take a look at the script below:

#!/bin/sh
# sendmail or "sendmail look alike" provided by postfix/exim/...
SENDMAIL=/usr/sbin/sendmail
## Or use custom "sendmail look alike" 
## e.g. msmtp which can send without local SMTP server
#SENDMAIL=/usr/bin/msmtp

[email protected]

$SENDMAIL -i -- $TO <<END_OF_EMAIL
Subject: My test message subject
To: $TO
X-Comment: Use empty line to separate email headers from email body

My test message body
END_OF_EMAIL

WARNING:
Sending messages with non US-ASCII letters (non english languages' letters) is more tricky.
It requires separate fixes for email headers and email body.

like image 159
AnFi Avatar answered Oct 19 '25 13:10

AnFi


To use sendmail you first need to install postfix:

>> sudo apt-get install postfix

youll have to configure the postfix settings by running >> dpkg-reconfigure postfix and following the instructions according to you. Then run >> service postfix reload to run the service.

Note: /usr/sbin/sendmail is aliased by using sendmail command. You can actually figure this out by typing which sendmail. So instead of typing in the file name you can just type in sendmail :)


To use sendmail:

Example:

>> sendmail [email protected]
Subject: Subject Line
... Email Body Here ...

Then press CTRL+D on a new line, this will send the email

if you find that your emails are slow or dont work properly this link has good intructions on what to do: https://www.digitalocean.com/community/questions/sendmail-is-slow-to-send-mail


If you want to add a File Attachment with sendmail I recommend uuencode. To use it you need to install:

>> sudo apt install sharutils

uuencode encodes a file into email friendly text (https://linux.die.net/man/1/uuencode)

Example:

uuencode /path/to/file.txt /path/to/file.txt | sendmail "[email protected]"

Just remember that you have to put the /path/to/file.txt twice since it takes an input file and an output or else it will run a command line entry below.

like image 41
g.meyer Avatar answered Oct 19 '25 13:10

g.meyer