Skip to main content
 首页 » 编程设计

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

2025年01月19日9itcoder

我正在尝试将一些变量传递给 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。提前致谢。

请您参考如下方法:

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) 
...