Having trouble with sending an email through SMTP Python

后端 未结 1 937
独厮守ぢ
独厮守ぢ 2021-02-04 20:18

So I\'m trying to send an email through SMTPlib with Python, but I can\'t get it to work. I read up on the Microsoft SMTP specs, and put them in accordingly, but I can\'t get it

1条回答
  •  情书的邮戳
    2021-02-04 21:15

    Try this. This works in Python 2.7.

    def send_mail(recipient, subject, message):
    
        import smtplib
        from email.MIMEMultipart import MIMEMultipart
        from email.MIMEText import MIMEText
    
        username = "sender@outlook.com"
        password = "sender's password"
    
        msg = MIMEMultipart()
        msg['From'] = username
        msg['To'] = recipient
        msg['Subject'] = subject
        msg.attach(MIMEText(message))
    
        try:
            print('sending mail to ' + recipient + ' on ' + subject)
    
            mailServer = smtplib.SMTP('smtp-mail.outlook.com', 587)
            mailServer.ehlo()
            mailServer.starttls()
            mailServer.ehlo()
            mailServer.login(username, password)
            mailServer.sendmail(username, recipient, msg.as_string())
            mailServer.close()
    
        except error as e:
            print(str(e))
    
    
    send_mail('recipient@example.com', 'Sent using Python', 'May the force be with you.')
    

    0 讨论(0)
提交回复
热议问题