How can I send email using Python?

后端 未结 3 1031
执念已碎
执念已碎 2020-12-15 11:43

I am writing a program that sends an email using Python. What I have learned from various forums is the following piece of code:

#!/usr/bin/env python
impor         


        
相关标签:
3条回答
  • 2020-12-15 12:16

    If message headers, payload contain non-ascii characters then they should be encoded:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    from email.header    import Header
    from email.mime.text import MIMEText
    from getpass         import getpass
    from smtplib         import SMTP_SSL
    
    
    login, password = 'user@gmail.com', getpass('Gmail password:')
    recipients = [login]
    
    # create message
    msg = MIMEText('message body…', 'plain', 'utf-8')
    msg['Subject'] = Header('subject…', 'utf-8')
    msg['From'] = login
    msg['To'] = ", ".join(recipients)
    
    # send it via gmail
    s = SMTP_SSL('smtp.gmail.com', 465, timeout=10)
    s.set_debuglevel(1)
    try:
        s.login(login, password)
        s.sendmail(msg['From'], recipients, msg.as_string())
    finally:
        s.quit()
    
    0 讨论(0)
  • 2020-12-15 12:16

    According to the error message, you use the localhost as the SMTP server, then the connection was refused. Your localhost didn't have an SMTP sever running I guess, you need to make sure the SMTP server you connect is valid.

    0 讨论(0)
  • 2020-12-15 12:18

    If you print the error message, you will likely get a comprehensive description of what error occurred. Try (no pun intended) this:

    try:
        # ...
    except Exception, error:
        print "Unable to send e-mail: '%s'." % str(error)
    

    If, after reading the error message, you still do not understand your error, please update your question with the error message and we can help you some more.


    Update after additional information:

    the error message

    socket.error: [Errno 111] Connection refused

    means the remote end (e.g. the GMail SMTP server) is refusing the network connection. If you take a look at the smtplib.SMTP constructor, it seems you should change

    server = smtplib.SMTP('smtp.gmail.com:587')
    

    to the following.

    server = smtplib.SMTP(host='smtp.gmail.com', port=587)
    
    0 讨论(0)
提交回复
热议问题