将多个变量传递给MIMETex的正确方法是什么

2024-04-16 07:56:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将一些变量传递给MIMEText,然后以纯文本电子邮件的形式发送这些变量。看起来很简单,但不管我做什么,我都没有得到预期的结果。在

以下是我所拥有的:

import cgi
from datetime import datetime
import smtplib
from email.mime.text import MIMEText

arguments = cgi.FieldStorage()

cid = arguments.getvalue('cid')
cin = arguments.getvalue('cin')
dn = arguments.getvalue('dn')
sttime = datetime.now().strftime('%m/%d/%Y_%H:%M:%S')

msg = MIMEText(cid, cin, sttime)  #Here's the problem
msg['Subject'] = '911 was dialed'
sender = 'first_last@domain.com'
recipient = 'user@gmail.com'
s = smtplib.SMTP('localhost')
msg['From'] = sender
msg['To'] = recipient
s.sendmail(sender, recipient, msg.as_string())

它发送电子邮件,但它只发送第一个变量(cid),并将其作为附件发送。我希望所有的变量都在邮件正文,而不是附件。在

如果我尝试打印传递给MIMEText的相同内容,它会产生我预期的结果:

^{pr2}$

如果我只是把一个文本串输入到MIMEText,它就会很好地发送。我在变量上做错了什么?我使用的是python2.7.14。提前谢谢。在


Tags: from文本importdatetime电子邮件msgargumentssender
1条回答
网友
1楼 · 发布于 2024-04-16 07:56:27

MIMEText构造函数接受3个参数:_text_subtype,和{}。在

  • _text是有效负载(消息体)。在
  • _subtype是mimetype子类型。默认值为'plain'将生成mimetype 'text/plain'。在
  • _charset是有效负载(_text)的字符编码。默认值是'us-ascii',这意味着不能包括unicode。要支持unicode,请使用'UTF-8'。在

因此,考虑到这一点,您要做的是构造有效负载并将其作为第一个参数(_text)传递给MIMEText。E、 g

要创建格式为的有效负载:

cid: 9545551212
cin: UserA
sttime: 04/12/2018_23:03:47

您可以执行类似的操作:

^{pr2}$

相关问题 更多 >