17

I was using Python for sending an email using an external SMTP server. In the code below, I tried using smtp.gmail.com to send an email from a gmail id to some other id. I was able to produce the output with the code below.

import smtplib
from email.MIMEText import MIMEText
import socket


socket.setdefaulttimeout(None)
HOST = "smtp.gmail.com"
PORT = "587"
sender= "somemail@gmail.com"
password = "pass"
receiver= "receiver@somedomain.com"

msg = MIMEText("Hello World")

msg['Subject'] = 'Subject - Hello World'
msg['From'] = sender
msg['To'] = receiver

server = smtplib.SMTP()
server.connect(HOST, PORT)
server.starttls()
server.login(sender,password)
server.sendmail(sender,receiver, msg.as_string())
server.close()

But I have to do the same without the help of an external SMTP server. How can do the same with Python?
Please help.

Nidhin Joseph
  • 1,461
  • 3
  • 15
  • 32
  • What do you exactly mean by `without the help of an external SMTP server.`? You don't want to use any SMTP server at all? Do you want to use your own SMTP server? Do you want to use some other SMTP server? – ρss Jun 17 '14 at 18:27
  • actually i want it with my own SMTP server. And if it is possible to achieve the same requirement without an SMTP server, then it is also ok for me. What I am trying to accomplish is sending an email from an anonymous custom email id to some other email id from my local pc. – Nidhin Joseph Jun 17 '14 at 18:29

2 Answers2

3

The best way to achieve this is understand the Fake SMTP code it uses the great smtpd module.

#!/usr/bin/env python
"""A noddy fake smtp server."""

import smtpd
import asyncore

class FakeSMTPServer(smtpd.SMTPServer):
    """A Fake smtp server"""

    def __init__(*args, **kwargs):
        print "Running fake smtp server on port 25"
        smtpd.SMTPServer.__init__(*args, **kwargs)

    def process_message(*args, **kwargs):
        pass

if __name__ == "__main__":
    smtp_server = FakeSMTPServer(('localhost', 25), None)
    try:
        asyncore.loop()
    except KeyboardInterrupt:
        smtp_server.close()

To use this, save the above as fake_stmp.py and:

chmod +x fake_smtp.py
sudo ./fake_smtp.py

If you really want to go into more details, then I suggest that you understand the source code of that module.

If that doesn't work try the smtplib:

import smtplib

SERVER = "localhost"

FROM = "sender@example.com"
TO = ["user@example.com"] # must be a list

SUBJECT = "Hello!"

TEXT = "This message was sent with Python's smtplib."

# 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()
aronadaal
  • 9,083
  • 1
  • 19
  • 33
Mansueli
  • 6,223
  • 8
  • 33
  • 57
  • 2
    I found this example somewhere and tried. But what I understood is whenever I am trying to send a mail with the help of this local fake smtp server, the method "process_message" handles the request. But here the method is doing nothing. So the emails are not getting delivered to the receiver's inbox. Please give me a direction. – Nidhin Joseph Jun 18 '14 at 01:45
  • @NidhinJoseph, look at this second script and give it a try, if it also doesn't works make sure you have those modules properly installed on your computer. – Mansueli Jun 18 '14 at 02:07
  • I'm trying to follow this examples, but nothing happens when I execute the second part of the code. The script doesn't return any error or status. How should I debug that trying to understand what's happenning ? – AlvaroAV Mar 16 '15 at 11:26
  • There are a lot of possible problems, such as your ISP not allowing a unsecured mail delivery, firewall on your PC. Or depending on your system whether you need a local smtp server running or not. – Mansueli Mar 16 '15 at 22:42
  • Probably don't suggest that you can create valid SMTP messages by pasting strings together. You can if your message is absolutely trivial, or you know exactly what you are doing; but the proper solution is to use the `email` library which takes care of everything and encapsulates all the myriad complications nicely. – tripleee Nov 23 '21 at 10:57
1

Most likely, you may already have an SMTP server running on the host that you are working on. If you do ls -l /usr/sbin/sendmail does it show that an executable file (or symlink to another file) exists at this location? If so, then you may be able to use this to send outgoing mail. Try /usr/sbin/sendmail recipient@recipientdomain.com < /path/to/file.txt to send the message contained in /path/to/file.txt to recipient@recipientdomain.com (/path/to/file.txt should be an RFC-compliant email message). If that works, then you can use /usr/sbin/sendmail to send mail from your python script - either by opening a handle to /usr/sbin/sendmail and writing the message to it, or simply by executing the above command from your python script by way of a system call.

mti2935
  • 11,465
  • 3
  • 29
  • 33