47

I've been trying to get my application to mail some outputted text to an email. For simplification I have isolated the script :

import smtplib
import sys
import os

SERVER = "localhost"

FROM = os.getlogin()
TO = [raw_input("To : ")]

SUBJECT = "Message From " + os.getlogin()

print "Message : (End with ^D)"
TEXT = ''
while 1:
    line = sys.stdin.readline()
    if not line:
        break
    TEXT = TEXT + line

# Prepare actual message

message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail

server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()

This script outputs :

    Traceback (most recent call last):
  File "/Users/christianlaustsen/Dropbox/Apps - Python/mail/smtplib_mail.py", line 32, in <module>
    server = smtplib.SMTP(SERVER)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 239, in __init__
    (code, msg) = self.connect(host, port)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 295, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 273, in _get_socket
    return socket.create_connection((port, host), timeout)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/socket.py", line 512, in create_connection
    raise error, msg
error: [Errno 61] Connection refused

So as you can see, the connection is being refused. I'm running Python 2.6 on Mac OS X Snow Leopard (if that's relevant).

I have tried searching around a lot, but haven't been able to find a solution. Any help will be appreciated.

AnFi
  • 10,493
  • 3
  • 23
  • 47
Tehnix
  • 2,020
  • 2
  • 18
  • 23
  • 3
    Your first step in debugging... Go to the shell and type 'telnet localhost 25' If that does not work, the problem does not belong in SO – Mike Pennington Apr 11 '11 at 10:31
  • 4
    @MikePennington or they could use Gabriel's answer, which is very helpful. ;) – Adam Aug 22 '13 at 21:29
  • 2
    I don't understand, https://docs.python.org/3/library/email.examples.html this is the first link given by google search and this question doesn't have a clear answer? How does one copy paste some piece of code that will work 100% and send an e-mail? – Charlie Parker May 01 '18 at 19:40

7 Answers7

60

If you start a local server as follows:

python -m smtpd -n -c DebuggingServer localhost:1025

Make sure to modify the mail-sending code to use the non-standard port number:

server = smtplib.SMTP(SERVER, 1025)
server.sendmail(FROM, TO, message)
server.quit()
Gabriel Ferrer
  • 833
  • 1
  • 7
  • 14
  • is it possible to not rely on running something before the actual python script starts? – Charlie Parker May 01 '18 at 21:03
  • I did this, and I see output when I run my script that makes me think it is successful, but the email never shows up in my inbox. Any tips for debugging? The output when I run my script is `--MESSAGE FOLLOWS-- ... --END MESSAGE--`. – Max Jun 10 '21 at 10:24
  • the debugging server is only meant for debugging, it doesn't actually send email. you need to run (or rent) an SMTP server for that – Josh Friedlander Mar 31 '22 at 13:03
16

My guess is that you do not have any SMTP server installed on your local machine.

If your emails are not sensitive, open a Gmail account and send your emails using it with Python.

Community
  • 1
  • 1
Adam Matan
  • 128,757
  • 147
  • 397
  • 562
  • Thank you, I was just stomped (don't know that much about smtp), since I could send a mail with sendmail and os.popen, I couldn't see why this would have been any different, but your answer clarifies it I guess :)... Thanks... – Tehnix Apr 11 '11 at 10:53
16

Start a simple SMTP server with Python like so:

python -m smtpd -n -c DebuggingServer localhost:1025
Raj
  • 3,791
  • 5
  • 43
  • 56
6

If you don't want to run a separate server, and if you're only using Unix, you can use this technique, copied from http://www.yak.net/fqa/84.html, and originally from the Python FAQ:

On Unix, it's very simple, using sendmail. The location of the sendmail program varies between systems; sometimes it is /usr/lib/sendmail, sometime /usr/sbin/sendmail. The sendmail manual page will help you out. Here's some sample code:

SENDMAIL = "/usr/sbin/sendmail" # sendmail location
import os
p = os.popen("%s -t" % SENDMAIL, "w")
p.write("To: cary@ratatosk.org\n")
p.write("Subject: test\n")
p.write("\n") # blank line separating headers from body
p.write("Some text\n")
p.write("some more text\n")
sts = p.close()
if sts != 0:
    print "Sendmail exit status", sts
Joshua Richardson
  • 1,827
  • 22
  • 22
4

I wanted to create something so that you could just copy paste it and have it work but this is the closest I got:

from email.message import EmailMessage
import smtplib
import os

def send_email(message,destination):
    # important, you need to send it to a server that knows how to send e-mails for you
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    # don't know how to do it without cleartexting the password and not relying on some json file that you dont git control...
    server.login('valid.username@gmail.com', 'password_for_gmail')
    msg = EmailMessage()
    msg.set_content(message)

    msg['Subject'] = 'TEST'
    msg['From'] = 'valid.username@gmail.com'
    msg['To'] = destination
    server.send_message(msg)

if __name__ == '__main__':
    send_email('msg','destination@email')

I feel the tutorial is misleading because it assumes without telling you very well that you already have a running server that sends e-mails for you...its odd. The only issue with my script is that I dont know how to make it work without having the cleartext password just written there but alas...at least it sends it? Just make a fake e-mail address or something...


made this question long time ago, so I don't remember what this means exactly put will put it here just in case:

It works only if you enable access for less secure apps: myaccount.google.com/lesssecureapps . I think you should put that in answer.

I probably went around it by using a fake email only for that or somehting like that or an email from my org can't remember. Good luck!

Charlie Parker
  • 5,884
  • 57
  • 198
  • 323
  • It really cannot be that easily done: `smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials p25sm6790964edm.60 - gsmtp')` You'll get that for correct combination of usr/pss. – Hrvoje Sep 10 '20 at 12:16
  • @Harvey what are you referring to? I've been using my solution for months now...daily... – Charlie Parker Sep 10 '20 at 15:03
  • 1
    It works only if you enable access for less secure apps: https://myaccount.google.com/lesssecureapps . I think you should put that in answer. – Hrvoje Sep 10 '20 at 15:15
  • sure why not, pasted your comment and upvoted your comment. – Charlie Parker Sep 10 '20 at 15:44
  • @Harvey did you try creating a fake email or something like that? Did it work for you? – Charlie Parker Sep 10 '20 at 15:45
  • 1
    Yes, it worked only after I enabled access for less secure apps. – Hrvoje Sep 10 '20 at 16:46
0

If you are root on your system then you may want to install opensmtpd. First this way you don't need to run the server manually (this service is enabled by default so after smtpd installation either start it manually or reboot your machine). Second, you don't need to change the line server = smtplib.SMTP(SERVER). To conclude, use yum install opensmtpd or the equivalent apt-get command.

e271p314
  • 3,841
  • 7
  • 36
  • 61
0

For whatever reason, I had difficulty passing server and port to the constructor, but not the connect function. This ended up working for me:

    s = smtplib.SMTP(timeout=30) #seconds
    s.connect(EMAIL_HOST, EMAIL_PORT)
    m = MIMEText('see subject')
    m['subject'] = 'sweet subject'
    m['from'] = EMAIL_FROM
    m['to'] = to_list  # comma-separated list of emails
    s.sendmail(m['from'], m['to'].split(','), m.as_string())
    s.quit()
Blaskovicz
  • 6,122
  • 7
  • 41
  • 50