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

时间:2019-08-02 06:59:45

标签: python email smtplib

我编写了一个使用smtplib发送电子邮件的代码,并给我“连接被拒绝”的错误

这是错误回溯

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

1 个答案:

答案 0 :(得分:1)

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