Sending mail from Python using SMTP

后端 未结 13 855
半阙折子戏
半阙折子戏 2020-11-28 17:27

I\'m using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I\'m missing ?

from smtplib import SM         


        
13条回答
  •  没有蜡笔的小新
    2020-11-28 18:17

    Here's a working example for Python 3.x

    #!/usr/bin/env python3
    
    from email.message import EmailMessage
    from getpass import getpass
    from smtplib import SMTP_SSL
    from sys import exit
    
    smtp_server = 'smtp.gmail.com'
    username = 'your_email_address@gmail.com'
    password = getpass('Enter Gmail password: ')
    
    sender = 'your_email_address@gmail.com'
    destination = 'recipient_email_address@gmail.com'
    subject = 'Sent from Python 3.x'
    content = 'Hello! This was sent to you via Python 3.x!'
    
    # Create a text/plain message
    msg = EmailMessage()
    msg.set_content(content)
    
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = destination
    
    try:
        s = SMTP_SSL(smtp_server)
        s.login(username, password)
        try:
            s.send_message(msg)
        finally:
            s.quit()
    
    except Exception as E:
        exit('Mail failed: {}'.format(str(E)))
    

提交回复
热议问题