Sending Emails with Python and Mailgun
-
I finally got round to install an email plugin for BitBangers. I chose the Mailgun plugin as it seemed the easiest to use and setup.
All you have to do is install the plugin, register for an account and add your API key.I went ahead and installed it. I created an account with Mailgun and I followed their instructions on how to add the correct DNS records. Once I had all the green ticks on their DNS checker page I added the API key and domain to the NodeBB Mailgun plugin control panel and sent a test email.
It worked!
My next task was to send out a mass email to a list of email address from an old forum I used to be an administrator on, OneHitGamer. This is what I found difficult. Mailguns documentation is great but I could not find a simple way to send an email with multiple lines for either python or curl through the command line.
After a lot of searching I found a blog post by Brad Gignac with some Python code and instructions on how to send emails with it.
import requests key = 'YOUR API KEY HERE' sandbox = 'YOUR SANDBOX URL HERE' recipient = 'YOUR EMAIL HERE' request_url='https://api.mailgun.net/v2/{0}/messages'.format(sandbox) request = requests.post(request_url, auth=('api', key), data={ 'from': '[email protected]', 'to': recipient, 'subject': 'Hello', 'text': 'Hello from Mailgun' }) print 'Status: {0}'.format(request.status_code) print 'Body: {0}'.format(request.text)
After installing requests for Python and changing the code I was able to use this tiny Python script to send an email to over 400 people.
-
Requests really does make HTTP usage so easy in Python; I came across and used it last week.