如何正确使用smtplib发送邮件?

How to send a email by using smtplib properly?

我写了一个代码来使用 smtplib 发送电子邮件并给我错误 'connection refused'

这是错误回溯

Traceback (most recent call last):
  File "mail.py", line 20, in <module>
    s = smtplib.SMTP('localhost')
  File "/usr/lib/python3.6/smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/lib/python3.6/smtplib.py", line 336, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/lib/python3.6/smtplib.py", line 307, in _get_socket
    self.source_address)
  File "/usr/lib/python3.6/socket.py", line 724, in create_connection
    raise err
  File "/usr/lib/python3.6/socket.py", line 713, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

python 文件

    import smtplib

    from email.message import EmailMessage

    msg = EmailMessage()
    msg.set_content('Hello, This message is sent by using python 
    smtplib')

    msg['Subject'] = 'Use of Smtp'
    msg['From'] = 'sen@gmail.com'
    msg['To'] = 'rec@gmail.com'

    # Send the message via our own SMTP server.
    s = smtplib.SMTP('localhost')
    s.send_message(msg)
    s.quit()

如果您想将邮件发送到gmail,您必须修改gmail 开发设置。 请参阅下面的更多信息:https://realpython.com/python-send-email/