Send email from Deta Micro. #301
Replies: 2 comments
-
I have a basic web hosting account in bigrock.in, and with that come email accounts with ready SMTP access, and through some clicks in their cpanel the email accounts become "verified", don't go into spam so easily. So, using the SMTP credentials from there, I have this api call in fastapi ready to send emails. Sharing python3.8 basic code that I've arrived at after multiple rounds of trial & error. Note that the SMTP credentials are in the # as per https://docs.python.org/3/library/email.examples.html
import smtplib
from email.message import EmailMessage
from email.headerregistry import Address
from email.utils import make_msgid
from fastapi import FastAPI
from typing import Optional, List
from pydantic import BaseModel
#############
# FUNCTIONS
def makeAddress(emails):
# have to split "[email protected]" into Address("name","name","domain.com"), and if multiple then have to string them together into tuple
if type(emails) == str:
holder = emails.strip().split('@')
if len(holder) != 2:
print("makeAddress: Invalid email id:",emails)
return os.environ.get('EMAIL_SENDER','')
return Address(holder[0],holder[0],holder[1])
elif type(emails) == list:
collector = []
for oneEmail in emails:
holder = oneEmail.strip().split('@')
if len(holder) != 2:
print("makeAddress: Invalid email id:",oneEmail)
continue
collector.append(Address(holder[0],holder[0],holder[1]))
# after for loop:
if len(collector): return tuple(collector)
# default
return os.environ.get('EMAIL_SENDER','')
def sendEmail(content, subject, recipients, cc=None, html=None):
'''
Emailing function.
'''
# from https://docs.python.org/3/library/email.examples.html
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = makeAddress(os.environ.get('EMAIL_SENDER',''))
msg['To'] = makeAddress(recipients)
if cc: msg['Cc'] = makeAddress(cc)
msg.set_content(content)
# adding html formatted body: from https://stackoverflow.com/a/58322776/4355695
if html:
msg.add_alternative(f"<!DOCTYPE html><html><body>{html}</body></html>", subtype = 'html')
print('to:',msg['To'])
# print('cc:',msg['Cc'])
# print('subject:',msg['Subject'])
# print(content)
# login to server and send the actual email
server = smtplib.SMTP_SSL(os.environ.get('EMAIL_SERVER',''), os.environ.get('EMAIL_PORT','')) # We are specifying TLS here
server.ehlo()
server.login(os.environ.get('EMAIL_SENDER',''),os.environ.get('EMAIL_PW',''))
status = server.send_message(msg)
server.close()
return status
#############
# FASTAPI
app = FastAPI()
#############
# API CALLS
class emailTestReq(BaseModel):
recipients: List[str]
subject: str
content: str
cc: Optional[str] = None
@app.post("/API/emailTest", tags=["email"])
def emailTest(req: emailTestReq, x_access_key: Optional[str] = Header(None)):
print("emailTest api call")
username, role = authenticate(x_access_key, allowed_roles=['admin'])
status = sendEmail(req.content, req.subject, req.recipients, req.cc)
print(f"Email status: {status}")
return {'message':'success', 'status':status} |
Beta Was this translation helpful? Give feedback.
-
@harshitsinghai77 use sendgrid or any email sending service you prefer. technically, you could also use your personal/professional email credentials to send emails. check out this guide of gmail |
Beta Was this translation helpful? Give feedback.
-
What's the best way to send Email using python with Deta Micro?
Beta Was this translation helpful? Give feedback.
All reactions