Raspberry Pi to receive SMS from sim cards?

Hi @Daniel252711

@Michael solution is probably the best but I wanted to shout out the work of another user here on the forums.

This post by @Dave65452 has a method of getting sms to a Raspberry Pi via a modem.

I remember being super impressed by this program.
The code includes Authorization Checks and Bash Shell Integration which isn’t relevant to you.
You might find it helpful to read through his git repo as an example of how you may approach it.

A lot of the magic seems to be handled by this software : Minicom.
https://help.ubuntu.com/community/Minicom

Concerning emailing from a Pi I made this code a while ago for … choosing my daughters name… long story. It uses google emails to achieve it’s goals. I’ve stripped it down to the minimum.

from selenium.webdriver.chrome.service import Service
from email.mime.text import MIMEText
import base64
import re
import os
import pickle
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from datetime import date, datetime, timedelta
from time import sleep

# Request all access (permission to read/send/receive emails, manage the inbox, and more)
SCOPES = ['https://mail.google.com/']

def Gmail_Authenticate():
	"""Authenticate this program to use Your Gmail
	Args:
	Returns:
	  A new Google API Service"""
	creds = None
	# the file token.pickle stores the user's access and refresh tokens, and is
	# created automatically when the authorization flow completes for the first time
	if os.path.exists("token.pickle"):
		with open("token.pickle", "rb") as token:
			creds = pickle.load(token)
	# if there are no (valid) credentials availablle, let the user log in.
	if not creds or not creds.valid:
		if creds and creds.expired and creds.refresh_token:
			creds.refresh(Request())
		else:
			flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
			creds = flow.run_local_server(port=0)
		# save the credentials for the next run
		with open("token.pickle", "wb") as token:
			pickle.dump(creds, token)
	return build('gmail', 'v1', credentials=creds)

def Create_Message(sender, to, subject, message_text):
	"""Create a message for an email.
	Args:
		sender: Email address of the sender.
		to: Email address of the receiver.
		subject: The subject of the email message.
		message_text: The text of the email message.
	Returns:
		An object containing a base64url encoded email object.
	"""
	# Create an HTML MIME message.
	message = MIMEText(message_text, 'html')
	message['to'] = to
	message['from'] = sender
	message['subject'] = subject
	# Encode the message
	b64_bytes = base64.urlsafe_b64encode(message.as_bytes())
	b64_string = b64_bytes.decode()
	return {'raw': b64_string}

def Send_Message(service, user_id, message):
	"""Send an email message.
	Args:
		service: Authorized Gmail API service instance.
		user_id: User's email address. The special value "me"
		can be used to indicate the authenticated user.
		message: Message to be sent.
	Returns:
		Sent Message."""
	try:
		message = (service.users().messages().send(userId=user_id, body=message).execute())
		print('Message Id: %s' % message['id'])
		return message
	except errors.HttpError as error:
		print('An error occurred: %s' % error)

def Pocket_Watch(tock, tick):
	"""Checks if it's day time or night time
	Args:
        Days: A list of Valid Days, reprosented as numbers where monday is 0, tuesday is 1, etc.
			eg [0, 1, 2, 3, 4) would be weekdays.
		Times: A tupple of valid times in 24hour format. eg (0900, 1800).

    Returns:
    	A Boolean, True if and only if the time and date is within the acceptable range."""
	if date.today().weekday() in tock:
		if tick[0] < int(datetime.now().strftime("%H%M")) < tick[1]:
			return True
	return False

def Hour_Glass(w):
	"""Counts down the minutes until the next event.
	Args:
		w: The number of minutes to wait before exiting recursive loop.

	Returns:
		An integer, 0 upon completion, else calls itself."""
	sleep(60)
	w = w - 1
	if w == 0:
		return w
	else:
		return Hour_Glass(w)

def Goodnight(t):
	"""Sleeps until the next day at the specified time
    Args:
        t: an integer reprosenting a the time, in 24 hour format.

    Returns:
    	Hour_Glass() (which will always be 0)"""
	
	hr = int(round(t / 100))
	mn = t % 100
	print(hr,mn)
	# sleep until 7AM
	t = datetime.today()
	tomorrow = t + timedelta(days=1)
	tomorrow_at_seven = datetime(tomorrow.year,tomorrow.month,tomorrow.day,hr,mn)
	dif_t = tomorrow_at_seven - t
	return Hour_Glass(round(dif_t.total_seconds() / 60))

# Mailing List
e_a = "a@gmail.com"
e_b = "b@gmail.com"
e_c = "c@gmail.com"
e_d = "d@gmail.com"
e_e = "e@gmail.com"
e_f = "f@gmail.com"
e_mails = [e_a, e_b, e_c, e_d, e_e, e_f]

# The Gmail API service
service = Gmail_Authenticate()

try:
	while True:
		if Pocket_Watch([0, 1, 2, 3, 4], (800, 1400)):
			pretty_mail = '''
			<!DOCTYPE html>
			<html>
			<head>
			</head>
			<body class="center">
			<h1>My Email to Myself</h1>
			</body>
			</html>
			'''

			for e in e_mails:
				print("---")
				print(f"Creating Email for {e}")
				dear_Jonny = Create_Message('me', e, "Mail", pretty_mail)
				print(f"Sending message to {e}")
				try:
					Send_Message(service, 'emailClientAddress@gmail.com', dear_Jonny)
				except:
					print(f"Failed to send message to {e}")

			print("\nSee you tomorrow <3\n-----")
			Goodnight(700)
		else:
			Goodnight(700)

except KeyboardInterrupt:
	print("\r\n interupt! \r\n I'll miss you!")
	
exit()
2 Likes