How to Send an E-Mail to Customers Programmatically

On occasion, you might have a use case where you might need to send an e-mail to customers upon only certain conditions, but in an automated way.  You can easily do this using a custom order workflow.  

In the example below, you can see that this will send the order receipt e-mail, but it can be easily changed to send any e-mail template that exists in your store configuration.  

public override bool Execute(OrderTaskContext context)
{
    try
    {
        var template = GetTemplate(context, HtmlTemplateType.NewOrderForAdmin);
        if (template != null)
        {
            var toAddress = context.HccApp.CurrentStore.Settings.MailServer.EmailForNewOrder;
            if (!string.IsNullOrEmpty(toAddress))
            {
                var mailMessage = new System.Net.Mail.MailMessage();
                template = template.ReplaceTagsInTemplate(context.HccApp, context.Order, context.Order.ItemsAsReplaceable());
                mailMessage = template.ConvertToMailMessage(toAddress);
                if (mailMessage != null)
                {
                    Hotcakes.Commerce.Utilities.MailServices.SendMail(mailMessage, context.HccApp.CurrentStore);
                }
            }
        }
    }
    catch
    {
        return false;
    }
    return true;
}
private HtmlTemplate GetTemplate(OrderTaskContext context, HtmlTemplateType type)
{
    var template = context.HccApp.ContentServices.HtmlTemplates.FindAll().Where(x => x.TemplateType == type).FirstOrDefault();
    return template;
}
Have more questions? Submit a request

Need More Help?

Do you need more assistance with this article? Please review your support options.