Sending mail from Python using SMTP

后端 未结 13 876
半阙折子戏
半阙折子戏 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:03

    The method I commonly use...not much different but a little bit

    import smtplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEText import MIMEText
    
    msg = MIMEMultipart()
    msg['From'] = 'me@gmail.com'
    msg['To'] = 'you@gmail.com'
    msg['Subject'] = 'simple email in python'
    message = 'here is the email'
    msg.attach(MIMEText(message))
    
    mailserver = smtplib.SMTP('smtp.gmail.com',587)
    # identify ourselves to smtp gmail client
    mailserver.ehlo()
    # secure our email with tls encryption
    mailserver.starttls()
    # re-identify ourselves as an encrypted connection
    mailserver.ehlo()
    mailserver.login('me@gmail.com', 'mypassword')
    
    mailserver.sendmail('me@gmail.com','you@gmail.com',msg.as_string())
    
    mailserver.quit()
    

    That's it

提交回复
热议问题