Send anonymous mail from local machine

2019-03-12 14: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.

回答1:

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()


回答2:

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.