如何在Python中发送邮件?

2 投票
2 回答
1268 浏览
提问于 2025-04-17 08:35

我在网上查了很多资料,但每次我尝试连接本地服务器时,都会出现“连接被拒绝”的错误。请问我需要用有效的邮箱地址登录才能发送邮件吗?这是我用的代码。

>>> import smtplib

>>> sender = 'from@fromdomain.com'

#this is my exact sender name bc i don't know if i need to use a valid email address or if i can just make up one since i dont need a password and username

>>> receiver = ['to@todomain.com']

#again, i dont know what to use for the receiver email address

>>> message = 'this is a test'

>>> s = smtplib.SMTP('localhost')

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    s = smtplib.SMTP('localhost')
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 242, in __init__
    (code, msg) = self.connect(host, port)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 302, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 277, in _get_socket
    return socket.create_connection((port, host), timeout)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 571, in create_connection
    raise err
error: [Errno 61] Connection refused

我遇到的问题就是这个连接被拒绝的错误。我在网上找了很多信息,但还是不知道怎么连接。

2 个回答

2

你电脑上有运行smtp服务器吗?“localhost”就是指你自己的电脑。

2

如果你想用 Gmail 来发送你的消息,可以参考这个链接里的代码:http://www.nixtutor.com/linux/send-mail-through-gmail-with-python/。这个代码应该很容易理解。

撰写回答