将多个变量传递给 MIMEText 的正确方法是什么
What is the proper way to pass multiple variables to MIMEText
我正在尝试将一些变量传递给 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
是payload(消息体)。
_subtype
是 mimetype 子类型。默认值为 'plain'
将导致 mimetype 'text/plain'
.
_charset
是payload的字符编码(_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)
...
我正在尝试将一些变量传递给 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
是payload(消息体)。_subtype
是 mimetype 子类型。默认值为'plain'
将导致 mimetype'text/plain'
._charset
是payload的字符编码(_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)
...