python localhost_通过python从localhost发送电子邮件到localhost

在将web服务投入生产前,作者在其本地机器上进行测试,其中包括邮件服务的测试。他们使用Python的email和smtplib库尝试发送邮件,但因未配置SMTP服务器而遇到错误。尽管如此,他们的服务设计是读取数据库记录并发送邮件。问题在于如何在未配置SMTP服务器的情况下测试邮件发送功能,并期望能在本地接收到由脚本发送的邮件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I'm building and testing a web service on my local machine before i put it in production. I want to test the mail service. I'm using the standard python email and smtplib libraries.

import smtplib

from email.mime.text import MIMEText

fp = open('textfile', 'rb')

msg = MIMEText(fp.read())

fp.close()

me = 'me_email@localhost'

you = 'me_again_email@localhost'

msg['Subject'] = 'The contents of %s' %fp

msg['From'] = me

msg['To'] = you

s = smtplib.SMTP('localhost')

s.sendmail(me, [you], msg.as_string())

s.quit()

I have not configured sendmail and hence it throws an error. But since I just want to test my web service I am not concerned if sendmail cant send an email right now. My service is designed to pulls some records off db and send them an email. So i want to know if this connection, python taking inputs from db and pushing an email is working. I want to receive the email on localhost sent via the script.

解决方案

An SMTP server needs to be configured for sending emails. Sending emails is not possible unless you configure an SMTP server. More information on using python smtplib can be found in pymotw.com, tutorialspoint.com and Python docs.