Send Email using Python and 1and1

The code you use to send email depends on whether the code is running on 1and1.com or on an external machine.

If you are on an external machine like your desktop, you use an SMTP script to send through your 1and1 email account. The following script called sendmail.py sends an email with python.

#!/usr/bin/python
import smtplib
from email.mime.text import MIMEText
me = "steve@example.com"
you = "sam@comcast.net"
password = "mypassword"
msg = MIMEText("This is a test message body.")
msg['Subject'] = 'Test message'
msg['From'] = me
msg['To'] = you
session = smtplib.SMTP("smtp.1and1.com", 587)
session.login(me, password)
session.sendmail(me, you, msg.as_string())
session.quit()

Run it like this: python sendmail.py

On 1and1 you need a mailbox type email. These types of emails have a password that you use in the script. It is easy to create a mailbox, if you don’t have one, by by logging into 1and1 and using their web interface.

If you copy this script to your web space on 1and1 and run it there, it will fail. 1and1 does not allow SMTP within 1and1. To send an email when running on 1and1 use this script:

#!/usr/bin/python
import os
mail_to = "sam@comcast.net"
mail_from = "steve@example.com"
subject = "test message"
header = """From: {0}
To: {1}
Subject: {2}
""".format(mail_from, mail_to, subject)
msg = header + "a test from me"
sendmail = os.popen("/usr/lib/sendmail -t", "w")
sendmail.write(msg)
sendmail.close()

Just open sendmail and write to it!