从本地计算机发送匿名邮件

Nid*_*eph 15 python email smtp anonymous

我使用Python使用外部SMTP服务器发送电子邮件.在下面的代码中,我尝试使用smtp.gmail.com从Gmail 密码发送电子邮件到其他ID.我能够使用下面的代码生成输出.

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()
Run Code Online (Sandbox Code Playgroud)

但是我必须在没有外部SMTP服务器的帮助下做同样的事情.如何用Python做同样的事情?
请帮忙.

Man*_*eli 3

实现这一目标的最佳方法是了解它使用的Fake SMTPsmtpd 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()
Run Code Online (Sandbox Code Playgroud)

要使用它,请将以上内容保存为 fake_stmp.py 并:

chmod +x fake_smtp.py
sudo ./fake_smtp.py
Run Code Online (Sandbox Code Playgroud)

如果您确实想了解更多细节,那么我建议您了解该模块的源代码。

如果这不起作用,请尝试 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()
Run Code Online (Sandbox Code Playgroud)

  • 我在某处找到了这个例子并尝试过。但我的理解是,每当我尝试借助本地假 smtp 服务器发送邮件时,“process_message”方法就会处理该请求。但这里该方法什么也没做。因此,电子邮件不会发送到收件人的收件箱。请给我一个方向。 (2认同)