1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 使用带有html正文的gmail帐户的SMTP python发送电子邮件

使用带有html正文的gmail帐户的SMTP python发送电子邮件

时间:2022-12-17 22:14:47

相关推荐

使用带有html正文的gmail帐户的SMTP python发送电子邮件

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

# Import smtplib to provide email functionsimport smtplib# Import the email modulesfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMEText# Define email addresses to useaddr_to = "xxxx@"addr_from = "xxxxx@"# Define SMTP email server detailssmtp_server = ""smtp_user = "xxxxxx@"smtp_pass = "xxxxxxx"# Construct emailmsg = MIMEMultipart("alternative")msg["To"] = *emphasized text*addr_tomsg["From"] = addr_frommsg["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 servers = smtplib.SMTP(smtp_server,587)s.login(smtp_user,smtp_pass)s.sendmail(addr_from, addr_to, msg.as_string())s.quit()解决方法:

在尝试登录之前添加这两行,它不会给您带来身份验证错误.

server.ehlo()server.starttls()

所以你的代码应该是这样的:

# 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@" addr_from = "xxxxx@" # Define SMTP email server details smtp_server = "" smtp_user = "xxxxxx@" 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." (your html code) # 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.ehlo() s.starttls() s.login(smtp_user,smtp_pass) s.sendmail(addr_from, addr_to, msg.as_string()) s.quit()来源:/content-1-418751.html

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。