如何使用 HTML 格式化包含表单数据的电子邮件?
How to format an email which contains form data using HTML?
我正在尝试使用 HTML 格式化电子邮件,每当有人填写表格以及表格数据时都会发送给我,例如{{ 名称 }}。目前,我设法使用“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
答案在email.mime.text模块中。该模块提供了一个函数,允许在您的“f”字符串中呈现 HTML 代码。必须添加此位:
message = f"<b>Client name:</b> {client_name}<br></br> <b>Email:</b> {client_email}"
message = MIMEText(message, "html")
完整代码如下:
from email.mime.text import MIMEText
MY_EMAIL = os.environ.get('MY_EMAIL')
MY_EMAIL_PASSWORD = os.environ.get('MY_EMAIL_PASSWORD')
message = EmailMessage()
message = f"<b>Client name:</b> {client_name}<br></br> <b>Email:</b> {client_email}"
message = MIMEText(message, "html")
message['Subject'] = "New form submitted"
message['From'] = MY_EMAIL
message['To'] = "an_email@hotmail.com"
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(MY_EMAIL, MY_EMAIL_PASSWORD)
smtp.send_message(msg_for_me)
我正在尝试使用 HTML 格式化电子邮件,每当有人填写表格以及表格数据时都会发送给我,例如{{ 名称 }}。目前,我设法使用“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
答案在email.mime.text模块中。该模块提供了一个函数,允许在您的“f”字符串中呈现 HTML 代码。必须添加此位:
message = f"<b>Client name:</b> {client_name}<br></br> <b>Email:</b> {client_email}"
message = MIMEText(message, "html")
完整代码如下:
from email.mime.text import MIMEText
MY_EMAIL = os.environ.get('MY_EMAIL')
MY_EMAIL_PASSWORD = os.environ.get('MY_EMAIL_PASSWORD')
message = EmailMessage()
message = f"<b>Client name:</b> {client_name}<br></br> <b>Email:</b> {client_email}"
message = MIMEText(message, "html")
message['Subject'] = "New form submitted"
message['From'] = MY_EMAIL
message['To'] = "an_email@hotmail.com"
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(MY_EMAIL, MY_EMAIL_PASSWORD)
smtp.send_message(msg_for_me)