如何使用 HTML 格式化包含表单数据的电子邮件?

我正在尝试使用 HTML 格式化电子邮件,每当有人填写表单以及表单数据(例如 {{ name }})时,该电子邮件就会发送给我。目前,我设法使用“f”字符串通过电子邮件传递表单数据。我不知道如何将字段标题(例如客户名称:、电子邮件:)设为粗体,以便它们不会与表单数据混合。


        MY_EMAIL = os.environ.get('MY_EMAIL')

        MY_EMAIL_PASSWORD = os.environ.get('MY_EMAIL_PASSWORD')

        

        message = EmailMessage()

        message['Subject'] = "New form submitted"

        message['From'] = MY_EMAIL

        message['To'] = "an_email@hotmail.com"

        message.set_content(f" Client name: {client_name}\n\n Email: {client_email}")

        with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:

            smtp.login(MY_EMAIL, MY_EMAIL_PASSWORD)

            smtp.send_message(message)

电子邮件的当前示例:


客户姓名: 杰克


电子邮件:blackjack@hotmail.com


期望的结果(“客户名称”,“电子邮件以粗体显示”):


客户姓名:杰克


电子邮件: blackjack@hotmail.com


蓝山帝景
浏览 228回答 1
1回答

慕无忌1623718

答案在 email.mime.text 模块中。该模块提供了一个函数,允许在“f”字符串中呈现 HTML 代码。必须添加这一点:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; message = f"<b>Client name:</b> {client_name}<br></br> <b>Email:</b> {client_email}"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; message = MIMEText(message, "html")这是完整的代码:from email.mime.text import MIMEText&nbsp; &nbsp; &nbsp; &nbsp; MY_EMAIL = os.environ.get('MY_EMAIL')&nbsp; &nbsp; &nbsp; &nbsp; MY_EMAIL_PASSWORD = os.environ.get('MY_EMAIL_PASSWORD')&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; message = EmailMessage()&nbsp; &nbsp; &nbsp; &nbsp; message = f"<b>Client name:</b> {client_name}<br></br> <b>Email:</b> {client_email}"&nbsp; &nbsp; &nbsp; &nbsp; message = MIMEText(message, "html")&nbsp; &nbsp; &nbsp; &nbsp; message['Subject'] = "New form submitted"&nbsp; &nbsp; &nbsp; &nbsp; message['From'] = MY_EMAIL&nbsp; &nbsp; &nbsp; &nbsp; message['To'] = "an_email@hotmail.com"&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; smtp.login(MY_EMAIL, MY_EMAIL_PASSWORD)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; smtp.send_message(msg_for_me)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python