Micropython学习交流群 学习QQ群:786510434 提供多种固件下载和学习交流。
Micropython-扇贝物联 QQ群:31324057 扇贝物联是一个让你与智能设备沟通更方便的物联网云平台
Micropython学习交流群 学习QQ群:468985481 学习交流ESP8266、ESP32、ESP8285、wifi模块开发交流、物联网。
Micropython老哥俩的IT农场分享QQ群:929132891 为喜欢科创制作的小白们分享一些自制的计算机软硬件免费公益课程,由两位多年从事IT研发的中年大叔发起。
esp32 smtp发送邮件micropython基于
micropython 实现邮件发送。
163邮箱好像不行,微软邮箱实验成功
代码如下:
下方位umail.py文件,保存与程序同一文件夹
# uMail (MicroMail) for MicroPython # Copyright (c) 2018 Shawwwn <shawwwn1@gmai.com> # License: MIT import usocket DEFAULT_TIMEOUT = 10 # sec LOCAL_DOMAIN = '127.0.0.1' CMD_EHLO = 'EHLO' CMD_STARTTLS = 'STARTTLS' CMD_AUTH = 'AUTH' CMD_MAIL = 'MAIL' AUTH_PLAIN = 'PLAIN' AUTH_LOGIN = 'LOGIN' class SMTP: def cmd(self, cmd_str): sock = self._sock; sock.write('%s\r\n' % cmd_str) resp = [] next = True while next: code = sock.read(3) next = sock.read(1) == b'-' resp.append(sock.readline().strip().decode()) return int(code), resp def __init__(self, host, port, ssl=False, username=None, password=None): import ussl self.username = username addr = usocket.getaddrinfo(host, port)[0][-1] sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM) sock.settimeout(DEFAULT_TIMEOUT) sock.connect(addr) if ssl: sock = ussl.wrap_socket(sock) code = int(sock.read(3)) sock.readline() assert code==220, 'cant connect to server %d, %s' % (code, resp) self._sock = sock code, resp = self.cmd(CMD_EHLO + ' ' + LOCAL_DOMAIN) assert code==250, '%d' % code if CMD_STARTTLS in resp: code, resp = self.cmd(CMD_STARTTLS) assert code==220, 'start tls failed %d, %s' % (code, resp) self._sock = ussl.wrap_socket(sock) if username and password: self.login(username, password) def login(self, username, password): self.username = username code, resp = self.cmd(CMD_EHLO + ' ' + LOCAL_DOMAIN) assert code==250, '%d, %s' % (code, resp) auths = None for feature in resp: if feature[:4].upper() == CMD_AUTH: auths = feature[4:].strip('=').upper().split() assert auths!=None, "no auth method" from ubinascii import b2a_base64 as b64 if AUTH_PLAIN in auths: cren = b64("\0%s\0%s" % (username, password))[:-1].decode() code, resp = self.cmd('%s %s %s' % (CMD_AUTH, AUTH_PLAIN, cren)) elif AUTH_LOGIN in auths: code, resp = self.cmd("%s %s %s" % (CMD_AUTH, AUTH_LOGIN, b64(username)[:-1].decode())) assert code==334, 'wrong username %d, %s' % (code, resp) code, resp = self.cmd(b64(password)[:-1].decode()) else: raise Exception("auth(%s) not supported " % ', '.join(auths)) assert code==235 or code==503, 'auth error %d, %s' % (code, resp) return code, resp def to(self, addrs, mail_from=None): mail_from = self.username if mail_from==None else mail_from code, resp = self.cmd(CMD_EHLO + ' ' + LOCAL_DOMAIN) assert code==250, '%d' % code code, resp = self.cmd('MAIL FROM: <%s>' % mail_from) assert code==250, 'sender refused %d, %s' % (code, resp) if isinstance(addrs, str): addrs = [addrs] count = 0 for addr in addrs: code, resp = self.cmd('RCPT TO: <%s>' % addr) if code!=250 and code!=251: print('%s refused, %s' % (addr, resp)) count += 1 assert count!=len(addrs), 'recipient refused, %d, %s' % (code, resp) code, resp = self.cmd('DATA') assert code==354, 'data refused, %d, %s' % (code, resp) return code, resp def write(self, content): self._sock.write(content) def send(self, content=''): if content: self.write(content) self._sock.write('\r\n.\r\n') # the five letter sequence marked for ending line = self._sock.readline() return (int(line[:3]), line[4:].strip().decode()) def quit(self): self.cmd("QUIT") self._sock.close()
下方为验证程序,包含wifi连接
# -*- coding: utf-8 -*- import umail import time import machine from machine import Pin import network try: import usocket as socket except: import socket import esp esp.osdebug(None) import gc gc.collect() led = machine.Pin(2,machine.Pin.OUT) io19 = Pin(19, Pin.IN) sent_flag = 0 #下面五个参数使用时修改成自己的,本例程中邮箱使用微软Hotmail邮箱,其他邮箱未经测试 wifi_ssid ="abc"#本地wifi的ssid名称 wifi_password ='13734606258' #本地wifi的密码 myusername = 'zzwceshi@hotmail.com' #发送端邮箱地址 mypassword = 'a1473698' #发送端邮箱密码 target_email = '1482847564@qq.com'#接收端邮箱地址 SMTP_SERVER = 'smtp.office365.com' #hotmail的smtp服务器地址 SMTP_SERVER_PORT = 587 #hotmail的smtp服务器端口 #连接本地wifi def connect_wifi(): wlan = network.WLAN(network.STA_IF) wlan.active(True) if not wlan.isconnected(): print("scaning......") all_ssid=str(wlan.scan()) if all_ssid.count(wifi_ssid)>0: print('connecting to:', wifi_ssid) else: print("not found AP") try: wlan.connect('abc', '13734606258') time.sleep(3) except Exception as e: raise e if wlan.isconnected(): pass else: print("connect wlan fail!!!") while not wlan.isconnected(): print("reconnect......") wlan.connect(wifi_ssid, wifi_password) if wlan.isconnected(): pass else: time.sleep(10) print('network config:', wlan.ifconfig()) def callback(p): global sent_flag if(io19.value()==1): time.sleep_ms(300) if(io19.value()==1): print("door open") led.value(1) sent_flag = 1 connect_wifi() sent_flag = 1 while(True): if(sent_flag == 1): try: print("door open") smtp = umail.SMTP(SMTP_SERVER, SMTP_SERVER_PORT) smtp.login(myusername, mypassword) smtp.to(target_email) smtp.write("From: Devices<"+myusername+">\r\n") #windows服务器不能单独识别\n 所以加上\r smtp.write("To: You<"+target_email+">\r\n") #如果出现报错可以尝试把\r\n换成\n smtp.write("Subject: WARNING!!!\r\n\n") smtp.write("苏乐乐大伞兵.\r\n") smtp.send() smtp.quit() print("Email was sent successfully!") led.value(0) except Exception as e: print("ERROR!!!") raise e
来源:https://blog.csdn.net/clonearm/article/details/127451692
Copyright © 2014 ESP56.com All Rights Reserved
执行时间: 0.0088140964508057 seconds