2025年5月5日月曜日

micropython and python gmail

https://randomnerdtutorials.com/raspberry-pi-pico-w-send-email-micropython/ 

ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー

umail.py::

 # Complete project details: https://RandomNerdTutorials.com/raspberry-pi-pico-w-send-email-micropython/

# uMail (MicroMail) for MicroPython Copyright (c) 2018 Shawwwn <shawwwn1@gmai.com> https://github.com/shawwwn/uMail/blob/master/umail.py 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 ssl

        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 = ssl.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 not ssl and CMD_STARTTLS in resp:

            code, resp = self.cmd(CMD_STARTTLS)

            assert code==220, 'start tls failed %d, %s' % (code, resp)

            self._sock = ssl.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()

ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー

# Rui Santos & Sara Santos - Random Nerd Tutorials

# Complete project details at https://RandomNerdTutorials.com/raspberry-pi-pico-w-send-email-micropython/

# Micropython lib to send emails: https://github.com/shawwwn/uMail

import umail

import network

import time

ssid = 'Buffalo-2G-8340'

password = ''


# Email details

sender_email = 'fseigojp@gmail.com'

sender_name = 'Raspberry Pi Pico'

sender_app_password = ''

recipient_email ='fseigojp@gmail.com'

email_subject ='Hello from RPi Pico W'


# Init Wi-Fi Interface

def init_wifi(ssid, password):

# Connect to WLAN

 wlan = network.WLAN(network.STA_IF)

 wlan.active(True)

 wlan.connect(ssid, password)


# Wait for Wi-Fi connection

 connection_timeout = 10

 while connection_timeout > 0:

    if wlan.status() >= 3:

        break

    connection_timeout -= 1

    print('Waiting for Wi-Fi connection...')

    time.sleep(1)


# Check if connection is successful

 if wlan.status() != 3:

    raise RuntimeError('Failed to establish a network connection')

 else:

    print('Connection successful!')

    network_info = wlan.ifconfig()

    print('IP address:', network_info[0])


    

# Connect to your network

init_wifi(ssid, password)


# Send the email

smtp = umail.SMTP('smtp.gmail.com', 465, ssl=True) # Gmail's SSL port


try:

    smtp.login(sender_email, sender_app_password)

    smtp.to(recipient_email)

    smtp.write("From:" + sender_name + "<"+ sender_email+">\n")

    smtp.write("Subject:" + email_subject + "\n")

    smtp.write("Hello from the Raspberry Pi Pico. Testing.")

    smtp.send()

    print("Email Sent Successfully")

    

except Exception as e:

    print("Failed to send email:", e)

finally:

    smtp.quit()

--------------------------------------------------------------------------------

https://note.com/noa813/n/nde0116fcb03f :: 

import smtplib, ssl

from email.mime.text import MIMEText

#上で作成したpyファイルから、account情報を読み込みます

import my_gmail_account as gmail


# 送信先のアドレスを登録します

send_address = "fseigojp@gmail.com"


# メインの関数になります

def send_test_email():

  msg = make_mime_text(

    mail_to = send_address,

    subject = "テスト送信",

    body = "Pythonでのメール送信です"

  )

  send_gmail(msg)


# 件名、送信先アドレス、本文を渡す関数です

def make_mime_text(mail_to, subject, body):

  msg = MIMEText(body, "html")

  msg["Subject"] = subject

  msg["To"] = mail_to

  msg["From"] = gmail.account

  return msg


# smtp経由でメール送信する関数です

def send_gmail(msg):

  server = smtplib.SMTP_SSL(

    "smtp.gmail.com", 465,

    context = ssl.create_default_context())

  server.set_debuglevel(0)

  server.login(gmail.account, gmail.password)

  server.send_message(msg)


# うまくいったら”OK”と表示させます

if __name__ == "__main__":

  send_test_email()

  print("ok")

0 件のコメント:

コメントを投稿