How to send and receive emails in mailgun (configured for a subdomain) from the root domain

solimanelefant picture solimanelefant · Apr 16, 2016 · Viewed 9.5k times · Source

Mailgun recommends creating DNS (TXT, MX,..) records for a subdomain, but states sending and receiving with the root domain is possible by later configuration. I created all necessary steps for mail.example.com at my registrar and at Mailgun (adding a domain, setting up routes, etc.). I can now receive and send emails to the configured [email protected].

What do I have to change now to be able to send and receive at [email protected]? What are the necessary changes at the registrar, in mailgun, and in my smtp settings at gmail (for sending from gmail via mailgun)?

Thank you very much!

Answer

Anton Egorov picture Anton Egorov · Apr 25, 2016

If you configure Mailgun for a subdomain, you can send emails from your main domain passing a proper to variable. For instance, using Node.js + nodemailer + nodemailer-mailgun-transport:

var nodemailer = require('nodemailer'),
    mg = require('nodemailer-mailgun-transport'),
    auth = { api_key: 'foobar', domain: 'mail.example.com' },
    nodemailerMailgun = nodemailer.createTransport(mg({ auth: auth }));

nodemailerMailgun.sendMail({
    from: '[email protected]',
    to: '[email protected]',
    subject: 'Hey you, awesome!',
    text: 'Mailgun rocks, pow pow!'
}, someCallback);

Or you can read about other methods of sending through an API in their docs. Anyway, even if your Mailgun is configured for a subdomain, you can send email from your main domain.

However (!) your MX records are configured for your subdomain, and hence you can only receive emails there. To be able to receive email to your main domain, add your main domain in Mailgun's control panel, e.g. not mail.example.com, but example.com, and make an according configuration in your DNS control panel for this main domain, example configuration for DigitalOcean's DNS for example.com (not subdomain):

TXT    @                v=spf1 include:mailgun.org ~all
TXT    krs._domainkey   k=rsa; p=MIGfM...blablabla
CNAME  email            mailgun.org.
MX     10               mxa.mailgun.org.
MX     10               mxb.mailgun.org.

Keep in mind, that Mailgun does not have mailbox functionality, it can only forward incoming emails, if you have an appropriate rule set. Most people delegate their main domain's MX records to a more manageable ESP, like Gmail. You can only have one set of MX records for a domain, so you have to choose, either Gmail, or Mailgun.