且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过SMTP Python发送电子邮件时遇到问题

更新时间:2023-01-23 17:46:19

尝试一下。这在Python 2.7中有效。

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.')