【问题标题】:What is the proper way to pass multiple variables to MIMEText将多个变量传递给 MIMEText 的正确方法是什么
【发布时间】:2018-09-23 07:57:11
【问题描述】:

我正在尝试将一些变量传递给 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 的相同内容,它会产生我期望的结果:

print(cid, cin, sttime)
('9545551212', 'UserA', '04/12/2018_23:03:47')

如果我只是将一串文本提供给 MIMEText,它就可以发送。我对变量做错了什么?我正在使用 python 2.7.14。提前致谢。

【问题讨论】:

  • 您要以什么格式发送这些变量?也就是说,您希望消息正文看起来如何?
  • @cpburnz 只是一串纯文本。我虽然在最后一行使用 msg.as_string() 完成了这一点。

标签: python python-2.7 mime smtplib


【解决方案1】:

MIMEText 构造函数接受 3 个参数:_text_subtype_charset

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

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

创建格式如下的有效负载:

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

你可以做类似的事情:

body = "cid: {}\ncin: {}\nsttime: {}".format(cid, cin, sttime)
msg = MIMEText(body)
...

【讨论】:

  • 正是我想要的!完美运行,非常感谢。
猜你喜欢
  • 2012-04-19
  • 2016-12-16
  • 2019-07-11
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 2021-11-22
相关资源
最近更新 更多