lev neiman dot com

29Mar/15

Making PHP / WordPress send email using custom sendmail

Recently I have had the pleasure of migrating a WordPress website which resulted in a peculiar problem - sending email functionality on the new server no longer worked.  After some digging around I found out that PHP has this mail function which uses the sendmail program to actually send your email.

Well after messing around with real sendmail for a good while and still not really understanding how to configure it properly, I decided to write my own sendmail.py script that uses my gmail and its app password to send out an email to whoever PHP/Wordpress wants to send an email to on my behalf.

After script was done I had to tell php to use it via sendmail_path = path to sendmail.py line inside php.ini which was located /etc/php5/apache2/php.ini on my Debian server. Then I just restarted apache server and voila, sending email worked!

Here is sendmail.py in all of its hacky glory:


#!/usr/bin/python

#this is replacement for sendmail that php can use to send its goddamn emails

import smtplib
import sys

def findToAddress(lines):
  for i, val in enumerate(lines):
  j = val.index("To: ")
  if j != -1:
    return val[j+4:]
  return ""

fromaddr = 'whatever@example.com'
lines = sys.stdin.readlines()
toaddrs = findToAddress(lines)
msg = ''.join(lines)

username = 'you@gmail.com'
password = 'your app password'

# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:25')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr,toaddrs, msg)
server.quit()