当消息是直接输入到函数中的字符串时,我可以发送电子邮件,但是当它是变量时,则无法发送电子邮件。
此代码有效:
import smtplib
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login("something@gmail.com", "somepassword")
server.sendmail(
"something@gmail.com",
"somethingelse@gmail.com",
"a manually typed string like this")
server.quit()
但是带有可变字符串的此代码不会:
import smtplib
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login("something@gmail.com", "somepassword")
someVariable = "any string"
server.sendmail(
"something@gmail.com",
"somethingelse@gmail.com",
someVariable)
server.quit()
更确切地说,第二个版本确实发送了电子邮件,但正文为空。没有字符显示。
如何使第二个版本正常工作?
print(someVariable)
和print(type(someVariable))
给出正确的(预期的)输出。
答案 0 :(得分:1)
我在Office365方面的亲身经历使我想到了这个解决方案:
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
msg['Subject'] = 'confirmation email'
msg['From'] = 'my.address@email.net'
msg['To'] = ", ".join(['your.address@email.net','another.address@email.net'])
body = 'Example email text here.'
msg.attach(MIMEText(body, 'html')) #set to whatever text format is preferred
最后是如何使其与当前脚本匹配的内容
server.sendmail('my.address@email.net','your.address@email.net',msg.as_string())
答案 1 :(得分:1)
事实证明,此方法行之有效,受到[these docs][1]
和rogersdevop的较早回答(对我而言不起作用)的启发:
def sendEmail(msge):
import smtplib
from email.mime.text import MIMEText
msg = MIMEText(msge)
me = 'something@gmail.com'
you = 'somethingelse@gmail.com'
msg['Subject'] = 'The subject line'
msg['From'] = me
msg['To'] = you
s = smtplib.SMTP_SSL('smtp.gmail.com', 465)
s.login("something@gmail.com", "somepassword")
s.send_message(msg)
s.quit()
答案 2 :(得分:0)
您可以尝试
import smtplib
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login("something@gmail.com", "somepassword")
server.sendmail(
"something@gmail.com",
"somethingelse@gmail.com",
"{}".format(someVariable))
server.quit()
我想您只需要将变量中的任何内容格式化为字符串