Page 1 of 1

How do I pull an email template and send an email?

Posted: Mon Dec 03, 2007 7:39 am
by AbleMods
I would like to make use of the AC7 templates and sendmail engine to send emails within my code.

Any chance you could point me towards the right functions to call so I don't have to dig through a bunch of controls? I have my own controls but I'd rather be as integrated with AC7 as possible.

Ideally I want to retrieve an email template into a string variable. For emailing, I need to be able to specify the to, cc and bcc as well as a file attachment. The super-duper bonus would be knowing the call to write a notes entry to the user notes of a given order.

I know you guys are busy but if it's a quick tidbit I could sure use the help.

I write in VB but I can translate C-Sharp well enough to get the point. Sorta.

Posted: Mon Dec 03, 2007 11:37 am
by sohaib

Code: Select all

  EmailTemplate template = [load your email template in question];

  //Set all the required velocity parameters used in the template
  template.Parameters[key1] = value1;
  template.Parameters[key2] = value2;
  template.Parameters[key3] = value3;

  //Just send :)
  template.Send(); 

Posted: Mon Dec 03, 2007 11:40 am
by AbleMods
That looks great. How do I retrieve a specific template from the table though i.e. by templateId?

Posted: Mon Dec 03, 2007 11:41 am
by sohaib
btw ... check load methods of EmailTemplateDatasource for loading...

A helpful note :
Whenever you want to load an object in AC7 you will find useful methods in that objects corresponding DataSource class....
Always check XXXDataSource class ... you will find something useful...

Posted: Tue Dec 11, 2007 7:31 am
by AbleMods
Ok, I can pull up a template, send it etc.

But I don't see a method for including a file attachment. Is that possible or should I code my own send routine that can handle file attachments?

Posted: Tue Dec 11, 2007 9:33 am
by sohaib
EmailTemplate class does not support attachments

Posted: Tue Dec 11, 2007 9:41 am
by AbleMods
Ok, no problem. The info helps tremendously, thank you very much - it's going to be very nice leveraging the AC7 template structure.

Posted: Tue Dec 11, 2007 6:51 pm
by AbleMods
Oh Man, I'm like 99% there!!

I'm trying to do a substitute in the template on $order.OrderId using the Template.Parameters method you suggested.

But the method isn't real clear on what it wants as a parameter. The description just says "Item(Key as Object) as Object".

I don't understand that - is it expecting me to declare a variable?

I thought it would be something like

Code: Select all

Template.Parameters("$order.Orderid") = SolunarOrder.Order.OrderId
But that no workie....thoughts?

Posted: Tue Dec 11, 2007 11:48 pm
by sohaib

Code: Select all

Template.Parameters("OrderId") = SolunarOrder.Order.OrderId;
Then you can use $OrderId in velocity template to refer to the OrderId

if you put

Code: Select all

Template.Parameters("Order") = SolunarOrder.Order;
You can use $Order.AnyProperytyOfOrderObject
including $Order.OrderId

Posted: Wed Dec 12, 2007 8:25 pm
by AbleMods
Ohhhhhhh :idea:

Re: You can add attachments to email templates

Posted: Fri Jun 12, 2009 3:39 pm
by ZLA
sohaib wrote:EmailTemplate class does not support attachments
But there is a work-around :!: The following code will load a template, add an attachment and then send it:

Code: Select all

                    EmailTemplate et = emailTemplates[0];
                    System.Net.Mail.MailMessage mm = et.GenerateMailMessages()[0];
                    mm.Attachments.Add(new System.Net.Mail.Attachment("D:\\WebSites\\MyWebSite\\App_Data\\XmlFiles\\sample.xml"));
                    System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("127.0.0.1");
                    client.Send(mm);
Use it in place of

Code: Select all

                    emailTemplates[0].Send();
I just tried it and it works but it hasn't gone through any severe testing so it's not quite production ready yet. But I had to share it.

Re: How do I pull an email template and send an email?

Posted: Fri Jun 12, 2009 6:19 pm
by AbleMods
Won't that bypass all the nVelocity scripting found in every email template?

Re: How do I pull an email template and send an email?

Posted: Fri Jun 12, 2009 9:49 pm
by nickc
AbleMods wrote:Won't that bypass all the nVelocity scripting found in every email template?
Yep. Here's a generic method I use send mail:

Code: Select all

        public static void SendSiteMail(string templateName, Hashtable parameters)
        {
            User customer;
            Vendor vendor;
            Order order;

            // by default, we only send from a production context
            if (SiteInformation.Current.IsProduction)
            {

                // hashtable contains objects for template replacements:
                // store, customer(user), basket, order, shipments, vendor, etc.
                // see template source for details (velocity references for "objectname" are ${objectname})
                NVelocityEngine nVengine = new NVelocityEngine();

                // load up the template
                EmailTemplate template = Token.Instance.Store.EmailTemplates.Find(delegate(EmailTemplate t) { return t.Name == templateName; });
                if (template != null)
                {
                    // load up the order, address info required
                    if (parameters.ContainsKey("order"))
                    {
                        order = parameters["order"] as Order;
                        if (order != null)
                        {
                            template.ToAddress = template.ToAddress.Replace("customer", String.Format("{0}", order.BillToEmail));
                            template.CCList = template.CCList.Replace("customer", String.Format("{0}", order.BillToEmail));
                            template.BCCList = template.BCCList.Replace("customer", String.Format("{0}", order.BillToEmail));
                        }
                    }

                    // do other address replacements
                    if (parameters.ContainsKey("customer"))
                    {
                        customer = parameters["customer"] as User;
                        if (customer != null)
                        {
                            // if an order is present, we've already replaced customer with billtoemail...
                            template.ToAddress = template.ToAddress.Replace("customer", String.Format("{0}", customer.LoweredEmail));
                            template.CCList = template.CCList.Replace("customer", String.Format("{0}", customer.LoweredEmail));
                            template.BCCList = template.BCCList.Replace("customer", String.Format("{0}", customer.LoweredEmail));
                        }
                    }
                    if (parameters.ContainsKey("vendor"))
                    {
                        vendor = parameters["vendor"] as Vendor;
                        if (vendor != null)
                        {
                            template.ToAddress = template.ToAddress.Replace("vendor", String.Format("{0}", vendor.Email));
                            template.CCList = template.CCList.Replace("vendor", String.Format("{0}", vendor.Email));
                            template.BCCList = template.BCCList.Replace("vendor", String.Format("{0}", vendor.Email));
                        }
                    }

                    // invoke velocity engine processing and send mail
                    nVengine.Init();
                    template.ToAddress = nVengine.Process(parameters, template.ToAddress);
                    template.FromAddress = nVengine.Process(parameters, template.FromAddress);
                    template.CCList = nVengine.Process(parameters, template.CCList);
                    template.BCCList = nVengine.Process(parameters, template.BCCList);
                    template.Subject = nVengine.Process(parameters, template.Subject);
                    template.Body = nVengine.Process(parameters, template.Body);
                    template.Send();
                }
            }
        }

Re: How do I pull an email template and send an email?

Posted: Sat Jun 13, 2009 8:45 am
by ZLA
nickc wrote:
AbleMods wrote:Won't that bypass all the nVelocity scripting found in every email template?
Yep. Here's a generic method I use send mail:
I hate to disagree with those who have more experience with AC than I but my code generates an email and doesn't include any of the special merchant fields that I use nVelocity to exclude. For example,

Code: Select all

#if ($orderItem.Inputs.Count > 0)
  #foreach( $input in $orderItem.Inputs )
    #if(!$input.Name.StartsWith("Regex") && $input.Name.Replace(" ", "") != "RequiredFieldsList" && !$input.Name.StartsWith("SG_"))
      <br /><b>$input.Name:</b> $input.InputValue 
      $input.InputValue
    #end
  #end
#end
My email did not have Required Fields List or any SG_ fields which were present in ac_OrderItemInputs for this order. I think the key is this piece of code:

Code: Select all

EmailTemplate et = emailTemplates[0];
System.Net.Mail.MailMessage mm = et.GenerateMailMessages()[0];
which takes care of all the addressing (which you'll notice my code doesn't even address) and rendering. This method exposes the underlying .NET mailmessage which I grab and send manually after adding my attachment.

I don't know if one of you is willing to try out my code and let me know the error of my ways but I'm curious to see if I've screwed up somewhere. Attached is a screenshot of the generated email.

Regards.

Re: How do I pull an email template and send an email?

Posted: Sat Jun 13, 2009 12:42 pm
by AbleMods
Ahh ok - I missed the call to the generatemailmessages() method. Yeah as long as you call generatemailmessages on the template, the resulting object will include any nvelocity processing contained in the original email template.