以下是我试图用来在Raspberry Pi中通过Python发送附件的Python代码,以将gmail / outlook电子邮件形式发送给带有附件的公司Outlook电子邮件。
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
fromaddr = "abc@gmail.com"
password = "password"
toaddr = "xyz@corp.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "sub_text"
body = "Test"
msg.attach(MIMEText(body, 'plain'))
# open the file to be sent
filename = "txtdata.txt"
attachment = open("/home/pi/txtdata", "rb")
p = MIMEBase('application', 'octet-stream')
p.set_payload((attachment).read())
encoders.encode_base64(p)
p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(p)
# creates SMTP session
try:
s = smtplib.SMTP('smtp.gmail.com', 587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(fromaddr, password)
text = msg.as_string()
s.sendmail(fromaddr, toaddr, text)
s.close()
except Exception as e:
print 'Error'
我在错误以下得到错误
Traceback (most recent call last):
File "/home/pi/scpt.py", line 30, in <module>
s = smtplib.SMTP('smtp.gmail.com', 587)
File "/usr/lib/python2.7/smtplib.py", line 256, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 316, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 291, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/lib/python2.7/socket.py", line 553, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
gaierror: [Errno -2] Name or service not known
谢谢!不知道是什么错误。是因为树莓派,我正在使用Python 2.7.9。我还授予了Gmail访问权限,以允许应用发送电子邮件。