Mailgun for emails in docker
Usually, even a small web application should send some emails: errors, registration, restore password, invitations, etc.
There are 3 solutions:
- use an existing account, like gmail: the main problem - you don’t know how many emails you can send before being marked as spam
- use own mail server: need to install, configure and support
- use email service, like sendgrid, mailgun: easy to configure, provide statistics and logs, can use default http port.
For some my small projects i choosed mailgun, it provides 10000 emails in month for free, for my needs it’s more than enough and after that it’s also not expensive. For django there is a email backend django-mailgun and it takes two minutes to switch to it.
Add environment variable in docker-compose.yml
web:
environment:
- MAILGUN_ACCESS_KEY
Setup email backend in django settings.
EMAIL_BACKEND = 'django_mailgun.MailgunBackend'
MAILGUN_ACCESS_KEY = os.environ.get('MAILGUN_ACCESS_KEY')
MAILGUN_SERVER_NAME = '<domain>'
For a php project it can be done with curl: apt-get install php5-curl
$curl_post_data=array(
'from' => 'from@email',
'to' => 'to1@email;to2@email',
'subject' => 'subject',
'text' => 'message',
'h:Reply-To' => 'reply@email'
);
$service_url = 'https://api.mailgun.net/v3/<domain>/messages';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "api:".$_ENV['MAILGUN_ACCESS_KEY']);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$curl_response = curl_exec($curl);
curl_close($curl);