【问题标题】:Send emal stmp office 365 : message empty发送电子邮件 smtp office 365:消息为空
【发布时间】:2016-12-20 10:07:39
【问题描述】:

我正在尝试用 Python 发送电子邮件

使用此代码使用 gmail 可以正常工作:

import smtplib

sender = 'xxx@xxx'
receivers = ['xxx@gmail.com']
message = "hello"

try:
  smtpObj = smtplib.SMTP('smtp.gmail.com:587')
  smtpObj.starttls()
  smtpObj.login('xxxx@gmail.com', 'my_password')
  smtpObj.sendmail(sender, receivers, message)
  smtpObj.quit()
  print("okay")

except:
  print("notokay")

但是当我在office 365上使用它时,电子邮件已发送但消息为空。

代码相同,但 'smtp.office365.com:587' 使用正确的登录名和密码。

【问题讨论】:

    标签: python smtp office365


    【解决方案1】:
    import smtplib
    from email.mime.text import MIMEText
    
    msg = MIMEText('hello')
    
    msg['Subject'] = 'Urgent message'
    msg['From'] = 'xxx@xxx'
    msg['To'] = 'xxx@gmail.com'
    
    s = smtplib.SMTP('smtp.gmail.com:587')
    s.starttls()
    s.login('xxx@gmail.com', 'my_password')
    s.sendmail('xxx@xxx', 'xxx@gmail.com', msg.as_string())
    s.quit()
    

    尝试以下操作,可能是因为您需要创建 MIMEText 上下文,以便 office365 接受格式。

    【讨论】:

    • 我试过了,sendMail 失败了。当我尝试打印 msg.as_string() 时,我遇到了这个问题:AttributeError: 'list' object has no attribute 'encode'
    • 天哪,这是我的错。我试图将列表接收者放在 msg['To'] 中。现在它工作正常。谢谢你!
    猜你喜欢
    • 2013-03-31
    • 2019-12-22
    • 1970-01-01
    • 2022-09-24
    • 2011-09-08
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    相关资源
    最近更新 更多