I have 3 functions -
- get_keyvault_secret() - To get the email password stored in Key Vault.
- send_email() - To create a MIMEMulitpart object and send an email to a recipient using the password received from the first function.
- main() - orchestrate the complete process. Send the KV URI and the secretname to 1st function and sends the password and other attributes to the 2nd function.
I'll attach my code here as well.
How do I resolve this issue?
def send_email(sender_email, receiver_email, subject, body, smtp_server, smtp_port, password):
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = receiver_email
message['Subject'] = subject
message.attach(MIMEText(body, 'plain'))
try:
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls(context=context)
server.ehlo()
server.set_timeout(10)
server.login(sender_email, password)
text = message.as_string()
server.sendmail(sender_email, receiver_email, text)
logging.info("Email sent successfully!")
return func.HttpResponse("Email sent successfully!", status_code=200)
except (smtplib.SMTPConnectError, smtplib.SMTPAuthenticationError, smtplib.SMTPDataError) as e:
logging.error(f"SMTP Error: {str(e)}")
return func.HttpResponse(f"SMTP Error: {str(e)}", status_code=500)
except socket.timeout:
logging.error("SMTP Connection Timeout")
return func.HttpResponse("SMTP Connection Timeout", status_code=500)
except Exception as e:
logging.error(f"Error: {str(e)}")
return func.HttpResponse(f"Error: {str(e)}", status_code=500)
finally:
server.close()
def main(req: func.HttpRequest) -> func.HttpResponse:
try:
payload_body = req.get_body()
KVUri = f"assume_a_Key_Vault_URI"
secretName = "assume_a_secretname"
password = get_keyvault_secret(KVUri,secretName)
smtp_server = "smtp.sendgrid.net"
smtp_port = 587
recipients = "assume_an_email_ID"
sender = "assume_an_email_ID"
subject = "Test Mail | Azure Functions | ADF Pipelines Status"
body = f"This is a Test Mail sent from an Azure Functions app. {str(payload_body)}"
response = send_email(sender, recipients, subject, body, smtp_server, smtp_port, password)
if response.status_code == 200:
return response
else:
error_message = f"Failed to send email. Status Code: {response.status_code}"
return func.HttpResponse(error_message, status_code=500)
except Exception as e:
logging.error(f"Error: {str(e)}")
error_message = f"Internal Server Error: {str(e)}"
return func.HttpResponse(error_message, status_code=500)