Sending Mail from EC2

Building a server from the ground up on Amazon’s EC2 platform, though awesome, has some challenges – big ones too! One of the most helpful things WordPress does is notify you of comments, new users registrations, etc. To do this, it has to talk to an SMTP server (preferably on the same box).

I tried to setup an SMTP server to send mail, and the messages kept getting blocked! It turns out that some of Amazon’s EC2 IP addresses are blocked! Don’t worry, there’s a legit way around this!

Roll up your sleeves, this is how you do it.

First things first, you need a SendGrid account. SendGrid is an SMTP relay service that’s perfect for situations like this one. The free plan allows for 200 messages per day. If you need more than that…what are you doing?! They have paid plans for you. After you sign up, you’ll get an email with your username and password. Hang on to it, you’re going to need it later.

To send mail, you need Postfix – there are other options, but I love keeping things simple.

In Ubuntu, or any other apt using Linux distro, type in:

sudo apt-get install postfix

or if your system uses yum:

yum install postfix

Simple, right? Well, sorta.

Next you’re going to have to tell it what kind of setup, in this case, on EC2, you want “Internet with Smarthost”.

From there, it’ll ask you questions that are entirely up to you.

It’s going to ask you for the smarthost address. Since we’re using SendGrid, use

smtp.sendgrid.net

Finish answering the other questions and you’re almost done.

Now, you have to edit the postfix config file. The installer can’t do everything for you – this ain’t Windows!

Type in

sudo pico /etc/postfix/main.cf

or

sudo vi /etc/postfix/main.cf

and past this in:

smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = static:yourSendgridUsername:yourSendgridPassword
smtp_sasl_security_options = noanonymous
smtp_tls_security_level = may
header_size_limit = 4096000
relayhost = [smtp.sendgrid.net]:587


Replace yourSendgridUsername and  yourSendgridPassword with your username and password.

Finally, you have to restart Postfix so it knows to use the relay. Do that with this command:

sudo /etc/init.d/postfix restart

That’s all there is to it. It’s not too painful. If you want to test it, create a dummy user and send the password to it. If you get the email, you’re good! If not, you might’ve missed a step or misread something in the installer.

Have you ever had to do anything like this?