Skip to content

Instantly share code, notes, and snippets.

@marlinspike
Created May 10, 2018 12:42
Show Gist options
  • Save marlinspike/f0c7cca7466f41d368b386610c6d75bf to your computer and use it in GitHub Desktop.
Save marlinspike/f0c7cca7466f41d368b386610c6d75bf to your computer and use it in GitHub Desktop.
Azure function to send email (works with GMail). You can use this as a WebHook URI
#r "Newtonsoft.Json"
using System;
using System.Net;
using Newtonsoft.Json;
using System.Net.Mail;
public static async Task<object> Run(HttpRequestMessage req, TraceWriter log)
{
log.Verbose($"Webhook was triggered!");
string jsonContent = await req.Content.ReadAsStringAsync();
dynamic data = JsonConvert.DeserializeObject(jsonContent);
bool isImportantEmail = bool.Parse(data.isImportant.ToString());
string fromEmail = data.fromEmail;
string toEmail = data.toEmail;
int smtpPort = 587;
bool smtpEnableSsl = true;
string smtpHost = "smtp.gmail.com"; // your smtp host
string smtpUser = "<your smtp address>"; // your smtp user
string smtpPass = "<your smtp password>"; // your smtp password
string subject = data.subject;
string message = data.message;
MailMessage mail = new MailMessage(fromEmail, toEmail);
SmtpClient client = new SmtpClient();
client.Port = smtpPort;
client.EnableSsl = smtpEnableSsl;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = smtpHost;
client.Credentials = new System.Net.NetworkCredential(smtpUser, smtpPass);
mail.Subject = subject;
if (isImportantEmail) {
mail.Priority = MailPriority.High;
}
mail.Body = message;
try {
client.Send(mail);
log.Verbose("Email sent.");
return req.CreateResponse(HttpStatusCode.OK, new {
status = true,
message = string.Empty
});
}
catch (Exception ex) {
log.Verbose(ex.ToString());
return req.CreateResponse(HttpStatusCode.InternalServerError, new {
status = false,
message = "Message has not been sent. Check Azure Function Logs for more information.",
sub = data.subject,
msg = data.message,
fromMail = fromEmail,
toMail = toEmail,
error = ex.ToString()
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment