Why You Need an Email Service
Managing an email server is a terrible experience. Emails fail to send. They get dropped. You get a ton of spam. You need to worry about backups and server security. Quite frankly, there's just too much to worry about when you can easily setup an email provider (for your inbox) and an email service (sending transactional/marketing emails).
Why spend the hours setting up and maintaining an email server when you can spend under $10/mo for both the provider and service? I don't know about you, but my time is worth more than that. Especially if it removes the possibility of me needing to dig through server logs to fix something.
Furthermore, once you run through this setup once, you'll realize just how simple it really is. Create an account, change a few DNS records, reuse your code, and boom. You're in business.
Why Mailgun?
I have a number of posts in the works and 3 of them utilize Mailgun. So instead of having a variation of the same steps in multiple places, I decided that I'd create one guide that I could reference elsewhere.
For now, this guide will only handle sending emails. You can setup Mailgun for your inbox as well, but I haven't needed that service yet. Instead, I'll either set up a noreply@example.com or setup an alias where replies go to my matt@example.com inbox.
Because I'm a developer and their tagline is "The Email Service for Developers." I've used other services but, in all honesty, Mailgun is the one that made the most sense to me. Other email services seem to gloss over why you do certain things (I'm looking at you, DNS records) whereas Mailgun is very straight forward as to why you're doing what.
It also offers both SMTP and API email sending, which is a definite perk. If I have the choice, I'll always use the API. But, in rare occasions (say, when I'm taking over an existing project), I'll be stuck using SMTP.
I won't cover SMTP in this post (or probably ever) because it's slower, offers more points of potential failure, usually requires more work to setup, and requires your email password. API sending is typically faster, has fewer points of failure, is easier to setup (in my opinion), and requires an API key that you can revoke and generate at will.
Creating Your Account
Creating a Mailgun account is pretty straight forward. They have an incredibly generous free tier that lets you send 10k emails per month, free. However, if you want to send to more than 5 different email addresses, you need to enter a credit card. They do this to prevent spam and, in my opinion, is pretty reasonable. You still don't get charged until you surpass 10k emails/month. I typically enter a card and have my clients do the same.
Choose Your Subdomain
Why am I using a subdomain when I want to send the emails from matt@example.com? It's to avoid conflicts and keep your domain in good standing. It's similar to having your frontend at example.com and your api at api.example.com. It lets you use each subdomain for something specific.
In this case, you're also using a different subdomain in order to keep your emails in good standing. The last thing you want to do is to send a marketing campaign from @example.com, get flagged for spam, resulting in all your regular emails are also getting flagged.
So, we do what Mailgun suggests. We use a subdomain. Mailgun also recommends splitting your transactional and marketing emails into separate subdomains, but I don't because I don't spam. You can use mail.example.com but I don't like to because I like to route mail.example.com to my email provider. Instead, I use mg.example.com
.

What's that DKIM Authority you ask? It's added security and proof that you are who you say you are. The SPF record allows a host to send emails on your behalf whereas a DKIM hash proves that you sent the email. A good analogy is that SPF proves that snail mail came from your house whereas DKIM proves that the snail mail came from you (and not your sister). It does this using public cryptography.
Covering public key encryption is a complex topic to cover in depth (and quite frankly, not something I'd be equipped to teach). I'll explain it in another post, but the values 1024 and 2048 will be the number of bits in your private key. Choosing 2048 will require extra steps when setting your TXT records below and you may need to reach out to your DNS provider. 1024 is simpler, what I'd recommend, and if you're using this guide, it's most likely secure enough. If you want to read more on the subject, check out this writeup on StackExchange.
Configuring Your DNS Records
The first few times I fiddled with DNS records, I didn't really know what I was doing. After a while, I started to realize that I was only changing A records when I was directing traffic to certain IP addresses. Then I was changing MX records to setup my gmail accounts. Then TXT records. And CNAME. Eventually, I started reading up on what these records actually do. I suggest you do the same. Until then, this is what you need to know about the DNS records set for Mailgun.
Note: Depending on your DNS provider, you may or may not need to append the ".example.com" to the end of the hostname. As far as I'm aware, most providers won't make you, so "mg.example.com" would be entered as "mg".
All email services will tell you to setup a few different types of records. Some will be required while others are optional.
TXT Records (required)

TXT records are the free-form DNS record. You can put pretty much any text here. There are, however, some standards. Mailgun will ask you to setup 2 of these. If you look at the beginning of the values, you'll notice that they actually mean something.
mg.example.com
has a value that starts withv=spf1
. That looks familiar for a reason. This is the TXT record that tells the world, "I have permission to send emails from this host."krs._domainkey.mg.example.com
is used to verify DKIM. Thekrs._domainkey
may vary, but the value structure will be the same and will start withk=rsa
. This may (or may not) mean much to you, but rsa is a specific algorithm used for encryption. Basically, the server that's sending the email sign the email with a one way hash generated with the private key (that only you should have, or in this case, Mailgun). The receiver will use the public key (the value afterp=
) to decode the signature in order to verify it came from you.
2048 DKIM Warning - You may need to reach out to your DNS provider to determine how to set this TXT record. Not all providers handle 255+ length TXT records the same way, and some don't handle them at all. TXT records have a max value length of 255 characters. If you use 1024 bit encryption, the value will be short enough that you can simply copy and paste the value into your DNS provider. If, however, you use 2048, the value will be too long. What you need to do instead, is break the value up into strings. So, break the string into 2 parts, wrap them each with double quotes, and put a space between the two strings. Put the two strings in a single TXT value.
# Provided Stringk=rsa; p=MIIBIjANB....IDAQAB# Edited String (there are no new lines, only spaces)"k=rsa; p=MIIBIjANB...iu2HUUlWa" "3lH5ekwG...IDAQAB"
It doesn't matter where you split the value, so long as neither chunk is longer than 255 characters. Verify with your DNS provider that this is the right method as it can vary based on provider.
MX Records (optional)

MX Records are the records used for your mailbox. I never set these up because I use gmail/outlook/protonmail for my email service. Having competing values in your MX records can result in you got getting your inbound mail. We don't want that so we'll leave that alone.
CNAME Record (optional)

CNAME Records are used to route traffic. We're basically saying that email.mg.example.com
should be handled by mailgun.org
. When anyone visits email.mg.example.com, mailgun.org will receive the request and handle it accordingly. In this case, it's where the email's pixel will be routed. Which effectively allows Mailgun to track when emails are opened.
Wait...
Now we wait for Mailgun to verify that you've added the TXT and CNAME records. Sometimes it only takes 5 minutes. Sometimes it takes hours. It can take up to 48 hours though. However, you can start writing your code, so you don't have to twiddle your thumbs while waiting :).
Sending a Test Email
Testing is super simple. Mailgun even gives you sample code to use. I used my setup for this domain below, make sure to swap in your values.
// Code provided by Mailgun (and edited for readability/promise usage)const mailgun = require('mailgun-js')const mg = mailgun({ apiKey: API_KEY, domain: 'mg.example.com'})// The following are both valid email address structures:// 'you@example.com'// 'You <you@example.com>'const data = { from: 'Fake Matt <fake@mattharris.io>', to: 'alias@mattharris.io', subject: 'Mailgun Example', text: 'Wow, this setup was easy!' // You can use html instead of text // html: `<html>...</html>`}try { await new Promise((resolve, reject) => { mg.messages().send(data, function (err, body) { if (err) return reject(err) return resolve(body) }) })}catch (err) { // Error handling goes here}
Run the code and you should receive an email in your inbox! By inspecting the email details, we see the following values. Now you know what the recipient will see :).


A few things to pay attention to:
- The recipient will have no idea that you used Mailgun to send the email. The only references to Mailgun is the subject (that I set) and the "mailed-by" and "signed-by". Developers (that use Mailgun) will probably be able to piece togethter how you sent the email, but that's it. And if you send from
m.example.com
, then they'll have no idea. Honestly, developers will know that you personally didn't send the emails, so who cares if they can tell from this information. They can check out your TXT records if they really wanted to know. - I can send from @example.com even if I registerred mg.example.com.
- I can send from an email that doesn't exist. "fake@mattharris.io" isn't a real address. That's why there's no profile image. (I created alias@mattharris.io for this example so I could actually receive the email).
Hopefully by now you understand more of what's happening behind the scenes/why you need to do the things Mailgun tells you to do.\
As always, feel free to post any comments/questions below and I'll get back to you. Or feel free to ask me on Twitter @mattharrio.
FAQs
How do I set up a mailgun? ›
Configure your Domain for Email
In Mailgun, navigate to Sending > Domains click Add New Domain. Add your domain and follow the setup. You will be given two TXT (SPF and DKIM), two MX, and a CNAME record. Update these records in your DNS provider.
- First, log in to the Mailgun Control Panel (if you have not already done so).
- Then, at the top-right corner of the page, click the Profile drop-down menu to expand its list of options.
- Next, click the API keys option. ...
- Click the eye icon to make the full API key visible.
...
Mailgun & Ghost Members
- Go to Labs and Members section.
- Click Expand in the Email Settings.
- Fill the From Address, members will receive emails from this address.
- Fill Mailgun region and Mailgun domain, from your Mailgun account.
- Fill Mailgun API Key.
For new users signing up, we offer a one-month Foundation Trial during which 5,000 emails are included for free. During the one-month trial, however, you actually can send up to 6,000 emails at no cost (due to our $1 minimum for payment processing).
What is the purpose of Mailgun? ›Mailgun lets you measure the business impact of your email campaigns with a/b testing, using tags on your email templates for real-time analytics. Know how your messages are rendering on different desktop clients like Outlook, Gmail, and more.
How many emails can I send with Mailgun? ›5,000 messages/month are included. There is a limit of 300 messages per day on the included sandbox domain. Data retention for Logs and the Events API is 1 day.
What does the secret key do? ›In symmetric cryptography a secret key (or “private key”) is a piece of information or a framework that is used to decrypt and encrypt messages.
What is the secret API key? ›The API Key and API Key Secret are essentially software-level credentials that allow a program to access your account without the need for providing your actual username and password to the software.
Is Mailgun API free? ›Free Email API For Easy Sending
Send, receive, and track emails with Mailgun's free email API.
Improve the deliverability of your cold email campaigns sent through a Mailgun inbox. Only from $12 per inbox!
Is Mailgun a mail server? ›
Mailgun is a third-party email service that is used to send outgoing emails through SMTP on the server. Those outgoing emails are maybe part of the email marketing campaigns or transactional emails such as password reset emails, order confirmation emails, user registration emails, etc.
Does Mailgun save emails? ›Internally, we store messages for 3 days for scheduled sends, troubleshooting and compliance verification. We're happy to announce that we have exposed this feature in our events API! # View a message using it's Mailgun storage key.
How can I send 500 emails a day? ›How can I send more than 500 emails a day on Gmail? Two of the easiest ways to bypass the 500 daily emails limit on Gmail include: Creating a different account to send emails to additional recipients. Creating Google Groups to send messages to a large group of individuals.
How can I send 10000 emails a day? ›- Step 2: Create your email list. ...
- Step 3: Create a sequence. ...
- Step 4: Compose your email. ...
- Step 6: Send or schedule the email. ...
- Set up DKIM, DMARC, SPF, and Custom domain.
Gmail + Mailgun Integrations
Zapier lets you send info between Gmail and Mailgun automatically—no code required. Triggers when you receive a new attachment (triggers once per attachment). automatically do this!
Mailgun is a set of powerful APIs that allow you to send, receive, track and store email effortlessly. MailChimp belongs to "Email Marketing" category of the tech stack, while Mailgun can be primarily classified under "Transactional Email". Some of the features offered by MailChimp are: Facebook Integration.
How do I link my domain to my Mailgun? ›Step 1: Add your domain to Mailgun
Then, within the left-hand navigation pane, click the Sending option to expand its list of suboptions. Next, click the Domains suboption. To add a domain, click the Add New Domain button. Fill in the required information and click the Add Domain button.
TextMagic, also a Mailgun customer, allows you to send notifications, alerts, reminders, confirmations and SMS marketing campaign messages to your customers, staff members and suppliers. On average, TextMagic customers are sending over 2.5M text messages around the world each month.
Can I send 500 emails at once? ›"You have reached a limit for sending mail"
You may see this message if you send an email to a total of more than 500 recipients in a single email and or more than 500 emails sent in a day. When you get this error, you should be able to send emails again within 1 to 24 hours.
Free Gmail account — If you use a free Gmail account, you are limited to sending a maximum of 500 emails in a 24-hour period, and a maximum of 100 addresses per email. Paid Google Workspace account — If you use a paid Google Workspace account, you are limited to sending a maximum of 2,000 emails in a 24-hour period.
How do I link my Mailgun to Gmail? ›
1) Go to settings in gmail 2) Click on Accounts 3) Send mail as: Click on Add another email address you own 4) Provide the email id you wish to appear as "Sender ID" 5) provide SMTP connection details which you can see once you login to your mailgun account and click on domain.
What is the difference between a private key and a secret key? ›A private key, also known as a secret key, is a variable in cryptography that is used with an algorithm to encrypt and decrypt data. Secret keys should only be shared with the key's generator or parties authorized to decrypt the data.
What is an example of secret keys? ›The secret key method of encryption, which involves the use of a single key, is used to encrypt and decrypt the information and is sometimes referred to as symmetric key cryptography. An excellent example of secret key encryption is the decoder ring you may have had as a child.
What is secret algorithm? ›A cryptographic algorithm that uses the same secret key for its operation and (if applicable) for reversing the effects of the operation (e.g., an HMAC key for keyed hashing or an AES key for encryption and decryption); also known as a secret-key algorithm. Source(s): NIST SP 800-133 Rev.
What can a hacker do with an API key? ›API hacking is a type of security testing that seeks to exploit weaknesses in an API. By targeting an API endpoint, you as an attacker can potentially gain access to sensitive data, interrupt services or even take over entire systems. It's said that more than 80% of all web traffic is now driven through API requests.
Can someone steal my API key? ›API Attacks Are On The Rise
Stolen or accidentally exposed API keys and secrets can easily be exploited by threat actors and used to access sensitive information, impersonate your mobile app or make API calls on its behalf.
The access can allow threat actors to read users' personal information, modify and delete users' information, access IP addresses and view a users' app users.
What is the cheapest email API provider? ›If price is a major consideration for your email API selection process, you'll want to look at Amazon SES: it's by far the cheapest email API service on the market.
Can you receive emails with Mailgun? ›You can define a list of routes to handle incoming emails and prioritize the sequence of their execution. Each route consists of a filter expression and an action. When a message is received, Mailgun evaluates the filter expression against it. If the expression is true, the action is executed.
Are Mailgun emails encrypted? ›By default, Mailgun attempts to take advantage of TLS when it is supported by the receiving mail server. In these exchanges, we also check the validity and legitimacy of the mail server's certificate. In situations where a server doesn't support TLS, we simply send the message unencrypted.
Is it legal to send mass emails? ›
Most country's email marketing laws stipulate that people need to give you permission to email them in order for you to send them campaigns. The definition of permission varies between each country's laws, but there are generally two types of permission: implied permission and express permission.
Does Mailgun work with Outlook? ›Mailgun + Microsoft Outlook Integrations
Zapier lets you send info between Mailgun and Microsoft Outlook automatically—no code required. Track Bounce Events via Callback URL. automatically do this!
- GMass. GMass is a powerful cold email software with built-in cold email automation tools that lets you run sales and marketing campaigns right from your Gmail account. ...
- Woodpecker. ...
- Lemlist. ...
- Yesware. ...
- Overloop. ...
- Gmelius. ...
- Streak. ...
- SalesHandy.
Mailgun is an SMTP service provider for transactional email and email marketing campaigns, offering robust features, support, and analytics—for free!
How do I send an email through Mailgun? ›- First, signup for a free account at Mailgun.com. ...
- The next step is to add your domain. ...
- Next, you will need to configure the domain for delivery. ...
- You will then need to add DNS records so that your email points to Mailgun.
Enter smtp.mailgun.org as your host and username as your mailgun email address. The port number can be saved as 587.
Do emails stay on your hard drive? ›Most email today, like Gmail, is cloud-based (IMAP). So on your hard drive you would have a cache of data, but your email is really stored on the server. However, you can set Mail to use the old "POP" system of email, which keeps a copy of each message as it comes in. But that isn't typical.
Where are Mailgun servers located? ›Mailgun is hosted within both the EU and the US, and you choose which region your data is processed in.
How much does it cost to send 100000 emails? ›For mass email sending, you can use Mailjet for $35 to send up to 100,000 monthly emails with no daily limit if you opt for the Essential plan.
How much does it cost to send 100k emails? ›...
weMail, The Ultimate Cheap Bulk Email Sender.
weMail + Amazon SES 100k Emails | Mailchimp 100k Emails |
---|---|
$19/month | $750/month |
How many emails can I send without getting blacklisted? ›
If you send 10,000 emails at once and there's a high bounce rate, you'll get blacklisted when the rate goes above 10%. Sending fewer emails as you warm up the IPs will help prevent that situation. Remember, more is not always better when it comes to sales leads.
What is considered a lot of emails per day? ›The average office worker receives around 121 emails every workday. They send less, with just 40 being the average per day – but that number still adds up to a very large amount of emails organization-wide. If your company has 1000 employees the team will send out 40,000 business emails in just one day.
How do I bulk email without spamming? ›- Correctly format headers. ...
- Ensure the email underwent a checkout. ...
- Use a special header. ...
- Include an Unsubscribe Link. ...
- Avoid using spam-like words. ...
- Don't use suspicious links and attachments. ...
- Check the design. ...
- Provide a plain-text version.
But the grand prize goes to Piyush Raka, who dethroned Chopra's record with what would appear to be 381,753 unread emails, a number so high it immediately drew questions of digital trickery from other people on Twitter.
Is Mailgun owned by Rackspace? ›Mailgun Technologies, Inc. was acquired by Rackspace in 2012 so their customers could easily integrate cloud-based email services into their applications and websites.
What is the difference between Mailgun and twilio? ›Mailgun belongs to "Transactional Email" category of the tech stack, while Twilio can be primarily classified under "Voice and SMS". Some of the features offered by Mailgun are: Optimized Queue. Scheduled Delivery.
Why is Mailgun not sending emails? ›Error: mailgun emails not delivered
This error will occur when Mailgun delivers your emails using a low-rated IP address. Low-rated IP addresses may cause the ISP to send the email to spam or reject it.
Mailgun is an SMTP service provider for transactional email and email marketing campaigns, offering robust features, support, and analytics—for free!
Is Mailgun an email provider? ›Mailgun (www.mailgun.com) is a transactional email service used by developers and information technology professionals to send, receive, and track emails using its powerful API.
Can I use Gmail with Mailgun? ›Setting up Custom Email Address on Gmail
Now you can receive emails on a custom domain and Mailgun will forward emails to your Gmail account.
Does Mailgun work with Gmail? ›
Gmail + Mailgun Integrations
Zapier lets you send info between Gmail and Mailgun automatically—no code required. Triggers when you receive a new attachment (triggers once per attachment). automatically do this!
SMTP sending made painless
Alongside our SMTP servers, Mailgun provides: Real-time email tracking and advanced analytics of your email program. Detailed logs to diagnose issues in sending. Advanced deliverability features to reduce bounce rates and spam complaints.
The enterprise email engine (Mailgun) uses the following IP Addresses: 166.78. 71.146. 23.253.