首页 > 解决方案 > 如何使用树莓派和 smtplib 通过电子邮件发送变量值

问题描述

我正在做这个项目,我有 3 个字符串变量,我想将它们的值通过电子邮件发送到电子邮件地址。我能够通过电子邮件发送纯文本消息;但是,我无法在其中包含这些变量值。以下是我的代码:

import serial
import smtplib
import time

serialport = serial.Serial('/dev/ttyUSB0', 115200, timeout = 0.5)
user= 'user@gmail.com'
password= 'password'
receiver= 'receiver@gmail.com
subject= 'Solar tracker status'
header = 'To: ' + email + '\n' + 'From: ' + email + '\n' + 'Subject: ' + 
subject
while True:
    line = serialport.readline()
    result = line.find(";")
    if result > 0:
            str = line.split(";")
            volt=str[0]
            power=str[1]
            temp=str[2]
            body = "\n" + + "Voltage: " + volt + "\n" + "Power: " + power + "\n" + "Temp: " + temp
            print header + '\n' + body
            s=smtplib.SMTP('smtp.gmail.com',587)
            s.ehlo()
            s.starttls()
            s.ehlo()
            s.login(email, password)
            s.sendmail(email, email, header + '\n\n' + body)
            s.quit

运行此脚本时,我收到此错误消息:

File "testserial.py", line 23, in <module>
    body = "\n" + + "Voltage: " + volt
TypeError: bad operand type for unary +: 'str'

我尝试使用 str(volt) 将变量转换为字符串,然后收到此错误消息:

File "testserial.py", line 23, in <module>
    str(volt)
TypeError: 'list' object is not callable

我无法理解这一点,因为它们最初是字符串格式,因为我能够使用 %s 将它们写入文本文件而无需转换它。

我想我只是不知道如何将变量传递到电子邮件的正文中。请帮忙!

标签: python-2.7smtpraspberry-pi3

解决方案


推荐阅读