Back to Portfolio

Build Your Own Custom Domain Email on AWS with Gmail

How to get an email address at your own domain without paying for a mailbox. Under a dollar a month. Everything in Terraform.

View on GitHub

Here is how to get an email address at your own domain without paying for a mailbox. I built mine on AWS. Mail comes in through Amazon SES and lands in my Gmail. I reply from Gmail and it goes out as my domain address. On the free tier it costs about 50 cents a month. That is just the Route 53 hosted zone, and new account credits can cover even that. Everything is in Terraform.

Why build it this way

How it works

Getting mail

  1. Someone emails YOUR_MAILBOX@YOUR_DOMAIN.
  2. Your domain's MX record sends it to SES. MX stands for Mail Exchange. It is the DNS record that says which server takes email for your domain.
  3. An SES receipt rule matches your address and scans it for spam and viruses.
  4. SES saves the raw email to S3.
  5. SES runs a small Lambda function.
  6. The Lambda changes the From line to your domain address, keeps the real sender in Reply-To, and sends it to your Gmail.

Why change From? SES won't send mail pretending to be from someone else's domain. Reply-To makes sure hitting reply still goes to the right person.

Sending mail

  1. You write in Gmail and pick your domain address in the From dropdown.
  2. Gmail sends it through SES using an SMTP login Terraform creates.
  3. SES signs it with DKIM. DKIM stands for DomainKeys Identified Mail. It is a digital signature that proves the email came from your domain and nobody changed it.
  4. The other person sees your domain address, not your Gmail.

What you are building

PieceWhat it does
Route 53 recordsMX, DKIM, SPF, and DMARC for your domain
SES identitiesYour domain, plus your Gmail while you are in the sandbox
S3 bucketHolds raw incoming mail, deleted after 90 days
LambdaForwards each email to Gmail
SES receipt ruleSends mail for your address to S3, then the Lambda
IAM userThe SMTP login Gmail uses to send as your domain

The cons

It is not a real mail provider. You need to know what you are building.

Sending takes two extra steps. Out of the box, this only receives. Your domain address can not send anything until you connect it to Gmail in Step 3. Until then, replies go out from your Gmail. After that, you are still in the SES sandbox. The sandbox only delivers to addresses you have verified. Forwarding to your own Gmail works because you verify it. Emailing a recruiter, a client, or anyone else bounces. So does replying to them. You have to request production access in Step 4. It is usually approved in about a day, but it can be denied.

Gmail is your mailbox. There is no separate inbox, webmail, or IMAP. Lose that Gmail and you lose your domain email too.

You can not sign in with it. Your domain address is not a Google account. It is an alias Gmail sends as. Regular email and password signups work fine, and the codes get forwarded to you.

Everything says "via YOUR_BRAND." The Lambda has to rewrite From. So Gmail filters that sort by sender won't work the way you would expect. Reply-To still points to the real person.

The sender's signature gets stripped. Forwarding changes the message, so their DKIM signature won't match anymore. Spam filtering is mostly up to the SES scan.

40 MB limit. SES caps messages at 40 MB in and out. Big attachments can fail.

One active rule set per region. If your account already receives email with SES, add your rule to that set.

Only some regions receive email. us-east-1, us-west-2, and eu-west-1 work. Check before you pick.

A long lived access key. Gmail's "Send mail as" needs a username and password. That means an IAM user with a static key. You can lock it down to your one address, but rotate it now and then.

Best practices for that key:

You are the help desk. If mail stops, it is on you. You will be reading Lambda logs and DNS records.

It is more work than a paid mailbox, but it is a good learning experience. If you just want email, pay for a mailbox. This is for people who want to learn how email works and want a real project to show for it.

Security risks to know

This setup works, but it has gaps. Here is what to watch for and what you can do about it now. Part 2 fixes these.

  1. Reporting spam can hurt your own domain. Forwarded mail comes from your domain through your SES account. If you hit "Report spam" in Gmail, that counts as a complaint against you. Too many and AWS can pause your sending. Delete junk instead, or set up a Gmail filter on [SPAM?].
  2. A leaked SMTP key lets someone send as you. It only works for your one address, but that is exactly what a scammer wants. If it ever leaks, delete the key in IAM and run terraform apply to make a new one.
  3. Your state file is not encrypted. It sits in your project folder with the SMTP password inside. Anyone who gets that folder gets the password. Keep it off shared drives and out of GitHub.
  4. Raw emails sit in S3 for 90 days. Anyone with S3 access to your AWS account can read them. Turn on MFA for your AWS account, and lower retention_days if you do not need them that long.
  5. People can fake email from your domain until you tighten DMARC. p=none only reports. Move to p=quarantine once your reports look clean, like in Step 4.
  6. Mail can arrive unencrypted. tls_policy = "Optional" accepts mail from servers that do not use TLS. Change it to "Require" if you are okay with some senders bouncing.
  7. Someone could flood your address. Every email costs a little and runs the Lambda. The budget alert from Before you start makes sure a surprise bill can not sneak up on you.

What it costs

On the free tier, about 50 cents a month. Past free tier, about 60 to 75 cents. Most of that is the Route 53 hosted zone. Your domain is a separate yearly cost. If you already have a personal website on your own domain in Route 53, like a portfolio site or your Cloud Resume Challenge, you are already paying for both. This just adds email.

These numbers assume a few hundred small emails a month.

ServiceAWS priceFree tierPast free tier
Route 53 hosted zone$0.50 per zone per monthNo free tier$0.50
SES receiving$0.10 per 1,000 emailsCovered by new account creditsAbout $0.10
SES sending$0.10 per 1,000 emailsCovered by new account creditsPennies
Lambda$0.20 per million requestsAlways free: 1 million requests per month$0
S3Storage plus requestsCovered by new account creditsPennies
CloudWatch LogsPer GB ingestedCovered by new account creditsPennies
TotalAbout $0.50, or $0 while credits lastAbout $0.60 to $0.75

Compared to paying for email

OptionMonthly costThe catch
Cloudflare Email Routing$0Receive only. Your DNS has to move to Cloudflare.
This buildAbout $0.10 to $0.25 on top of the hosted zoneYou set it up and fix it yourself
iCloud+$0.99 for the 50 GB planYou use iCloud Mail, not Gmail.
Zoho Mail Lite$1 per user for 5 GBYou live in Zoho's app, not Gmail
Fastmail Individual$5 billed yearlyOne user. Great app, but it is not Gmail.
Google Workspace Business Starter$7 per user billed yearlyA real Google account. "Sign in with Google" works.

If your domain already lives in Route 53, you are paying for the hosted zone either way. So this build only adds pennies. The only thing cheaper is free forwarding like Cloudflare, and that can not send. iCloud+ comes close if you are already on Apple. Everything else costs more, and none of them let you keep Gmail.

Before you start

What you need:

Fill in your values before you start. Every placeholder in this post is one of these:

PlaceholderWhat it isExample
YOUR_DOMAINYour domain, with a Route 53 hosted zoneexample.com
YOUR_MAILBOXThe part before the @hello
YOUR_GMAILWhere mail gets forwardedsomeone@gmail.com
YOUR_REGIONAn SES region that receives emailus-east-1
YOUR_BRANDShows in Gmail as "Sender via YOUR_BRAND"MyBrand
YOUR_NAMEYour name in Gmail's Send mail asYour Name

Pick a region that receives email. Not every region does. us-east-1, us-west-2, and eu-west-1 all work. Check the SES receiving endpoints for the current list.

Set up a budget alert before you build anything. AWS won't warn you if something starts costing money. A budget will.

  1. In the AWS console, search for Budgets.
  2. Click Create budget, then Use a template, then Monthly cost budget.
  3. Set an amount you would be surprised to see, like $10.
  4. Enter the email you want alerts sent to.
  5. Click Create budget.

Step 1: Get the code

All the code is on GitHub.

git clone https://github.com/JenMagruder/aws-domain-email.git
cd aws-domain-email
cp terraform.tfvars.example terraform.tfvars

On Windows PowerShell, use copy instead of cp.

Open terraform.tfvars and put in your values from the table above. You do not need to change anything else.

FileWhat it does
main.tfThe whole build: DNS, SES, the S3 bucket, the Lambda, the receipt rule, and the SMTP user
variables.tfThe settings you can change
terraform.tfvars.exampleA template for your own values
versions.tfTerraform version and providers
outputs.tfPrints your SMTP login after you apply
lambda/forwarder.pyForwards each email to Gmail
.gitignoreKeeps your secrets and your real values off GitHub
Keep your secrets off GitHub. Your state file will have your SMTP password in it, in plain text. terraform.tfvars has your real domain and Gmail. The repo's .gitignore already keeps both off GitHub. If you push your own copy, run git status first and make sure neither one shows up. Never paste the SMTP password anywhere, including the README, commit messages, or screenshots.

Step 2: Preflight checks and apply

Do these before you apply. Each one catches something that is a pain to fix later.

1. No MX record yet. If your domain already gets email somewhere, this would take it over.

# Mac or Linux
dig MX YOUR_DOMAIN +short

# Windows PowerShell
Resolve-DnsName YOUR_DOMAIN -Type MX

Nothing back, or just an SOA line, means you are good.

2. No active receipt rule set. Only one can be active per region.

aws ses describe-active-receipt-rule-set --region YOUR_REGION

No output means you are good.

3. Right account. The hosted zone has to be in the account you deploy to.

aws route53 list-hosted-zones-by-name --dns-name YOUR_DOMAIN --query "HostedZones[0].Name" --output text

It should print your domain with a dot at the end.

4. Nothing blocks IAM users. If your account is in an AWS Organization with an SCP that denies iam:CreateUser, set create_smtp_user = false. You will still get mail. You just won't be able to send from Gmail.

Then apply:

terraform init
terraform plan
terraform apply

Read the plan before you type yes. It should say 30 to add, 0 to change, 0 to destroy. If anything says change or destroy, stop and figure out why.

Step 3: Verify, test, and connect Gmail

Check YOUR_GMAIL for an email from Amazon Web Services and click the link. The Lambda can not forward to you until you do this.

Then check that your domain verified:

aws sesv2 get-email-identity --email-identity YOUR_DOMAIN --region YOUR_REGION \
  --query "{dkim:DkimAttributes.Status,mailfrom:MailFromAttributes.MailFromDomainStatus}"

Both should say SUCCESS. If they say PENDING, give DNS up to an hour.

Send a test from any other email account to YOUR_MAILBOX@YOUR_DOMAIN. In about a minute it should show up in your Gmail as "Their Name via YOUR_BRAND."

Did not show up? Check the Lambda logs:

aws logs tail /aws/lambda/YOUR_DOMAIN_WITH_DASHES-mail-forwarder --since 30m --region YOUR_REGION

YOUR_DOMAIN_WITH_DASHES is your domain with dashes instead of dots. So example.com becomes example-com.

Get your SMTP login:

terraform output smtp_username
terraform output -raw smtp_password

The username is fine to see. The password is a real secret. Copy it straight into Gmail and do not paste it anywhere else.

Set up Gmail "Send mail as" on a computer (the Gmail phone app does not have these settings):

  1. In Gmail, click the gear, then See all settings.
  2. Open the Accounts and Import tab.
  3. Under Send mail as, click Add another email address.
  4. Fill in your name and YOUR_MAILBOX@YOUR_DOMAIN. Check "Treat as an alias." Click Next Step.
  5. SMTP Server: email-smtp.YOUR_REGION.amazonaws.com, Port: 587, enter your username and password, TLS selected. Click Add Account.
  6. Gmail emails a confirmation code to your domain address. Your forwarder sends it right back to Gmail. Click the link or enter the code.
  7. Under When replying to a message, pick "Reply from the same address the message was sent to."

Now your domain address shows up in the From dropdown. When you reply to mail sent to it, Gmail uses it automatically.

Step 4: Get out of the SES sandbox

Until you do this, your domain address can only send to addresses you have verified in SES. Getting mail works fine. Sending to anyone else bounces, even a reply.

In the SES console for YOUR_REGION, go to Account dashboard, then Request production access. Here is a sample use case description. Change it so it is true for you:

Personal business email for one address, YOUR_MAILBOX@YOUR_DOMAIN. I send one to one replies to clients and contacts from Gmail through SES SMTP. Low volume, under 50 emails a day. The domain is verified with DKIM, a custom MAIL FROM domain, SPF, and DMARC. Bounces and complaints go to the same mailbox. I do not send marketing or bulk email.

AWS usually answers in about a day. Be specific and honest. Vague requests get denied.

Once approved, send from your domain address to an account that is not yours. Have them look at the original message headers. You want DKIM: PASS and SPF: PASS for your domain.

After a couple weeks, look at the DMARC reports that come to your address. If everything real is passing, change the DMARC record in main.tf to:

v=DMARC1; p=quarantine; rua=mailto:YOUR_MAILBOX@YOUR_DOMAIN; fo=1

That tells other servers to send anything that fails your checks to spam. It stops people from faking emails from your domain.

Gotchas I hit along the way

ProblemWhat happenedFix
Terraform upgrade did not stickChocolatey needs an admin window, and a failed try left a stale shimRun as admin, then choco install terraform --force -y

If you take one thing from this post: always read the plan before you type yes. It tells you exactly what is about to change. If anything says change or destroy and you did not expect it, stop.

If you build this, let me know how it goes.

Coming soon: Part 2. I will show you how to take this project further and fix the security risks above.


View the full project on GitHub or connect with me on LinkedIn.

Back to Portfolio