使用html正文从Gmail帐户使用SMTP python发送电子邮件

Ahs*_*tar 3 python smtp

我正在尝试使用SMTP库从python脚本使用gmail帐户发送电子邮件。正常的邮件正文可以正常工作。但是当我尝试使用HTML正文发送它时。它不允许我发送。

# Import smtplib to provide email functions
import smtplib

# Import the email modules
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Define email addresses to use
addr_to   = 'xxxx@localdomain.com'
addr_from = "xxxxx@gmail.com"

# Define SMTP email server details
smtp_server = 'smtp.gmail.com'
smtp_user   = 'xxxxxx@gmail.com'
smtp_pass   = 'xxxxxxx'

# Construct email
msg = MIMEMultipart('alternative')
msg['To'] = *emphasized text*addr_to
msg['From'] = addr_from
msg['Subject'] = 'Test Email From RPi'

# Create the body of the message (a plain-text and an HTML version).
text = "This is a test message.\nText and html."
html = """\
<html>
  <head></head>
  <body>
    <p>This is a test message.</p>
    <p>Text and HTML</p>
  </body>
</html>
"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)

# Send the message via an SMTP server
s = smtplib.SMTP(smtp_server,587)
s.login(smtp_user,smtp_pass)
s.sendmail(addr_from, addr_to, msg.as_string())
s.quit()
Run Code Online (Sandbox Code Playgroud)

小智 5

在尝试登录之前添加这两行,它不会给您验证错误。

server.ehlo()
server.starttls()
Run Code Online (Sandbox Code Playgroud)

因此,您的代码应如下所示:

    #导入smtplib以提供电子邮件功能
    导入smtplib

    #导入电子邮件模块
    从email.mime.multipart导入MIMEMultipart
    从email.mime.text导入MIMEText

    #定义要使用的电子邮件地址
    addr_to ='xxxx@localdomain.com'
    addr_from =“ xxxxx@gmail.com”

    #定义SMTP电子邮件服务器详细信息
    smtp_server ='smtp.gmail.com'
    smtp_user ='xxxxxx@gmail.com'
    smtp_pass ='xxxxxxx'

    #构建电子邮件
    msg = MIMEMultipart('alternative')
    msg ['To'] = *强调文字* addr_to
    msg ['From'] = addr_from
    msg ['Subject'] ='测试来自RPi的电子邮件'

    #创建消息的正文(纯文本和HTML版本)。
    text =“这是一条测试消息。\ n文本和html。”

    (您的HTML代码)

    #记录两个部分的MIME类型-文本/纯文本和文本/ html。
    第1部分= MIMEText(text,'plain')
    第2部分= MIMEText(html,'html')

    #将零件附加到消息容器中。
    #根据RFC 2046,在这种情况下,是多部分消息的最后一部分
    #HTML消息是最佳和首选的。
    msg.attach(part1)
    msg.attach(part2)

    #通过SMTP服务器发送邮件
    s = smtplib.SMTP(smtp_server,587)
    s.ehlo()
    s.starttls()
    s.login(smtp_user,smtp_pass)
    s.sendmail(addr_from,addr_to,msg.as_string())
    s.quit()