How can I send email using Python?

后端 未结 3 1030
执念已碎
执念已碎 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()
    

提交回复
热议问题