Hello Everyone,
In Web Form For Marketers, I was creating a 'Custom Email Sending Save Action' & wanted to send E-mail to Recipient from front-end. I was using 'Gmail SMTP' for sending Email. For this I used below code for web.config:
And now in my class file implements 2 interfaces: ISaveAction & ISubmit and override their methods. The code is below:
In Web Form For Marketers, I was creating a 'Custom Email Sending Save Action' & wanted to send E-mail to Recipient from front-end. I was using 'Gmail SMTP' for sending Email. For this I used below code for web.config:
<setting name="MailServer" value="smtp.gmail.com"/>
<setting name="MailServerPort" value="587"/>
And in the end of web.config before </configuration> added below code:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network enableSsl="true" />
</smtp>
</mailSettings>
</system.net>
And now in my class file implements 2 interfaces: ISaveAction & ISubmit and override their methods. The code is below:
public void Execute(Sitecore.Data.ID formid, AdaptedResultList fields, params object[] data)
{
NameValueCollection formData = new NameValueCollection();
foreach (AdaptedControlResult acr in fields)
{
formData[acr.FieldName] = acr.Value;
}
try
{
// get field values of form
string emailTo = formData["To"];
string emailFrom = formData["From"];
string personalMsg = formData["Message"];
bool result = false;
if (!string.IsNullOrEmpty(emailFrom) && !string.IsNullOrEmpty(emailTo))
{
// send mail
result = SendEmail(emailTo, emailFrom, personalMsg);
}
// if mail sending fail then show error massege
if (result == false)
{
Sitecore.Diagnostics.Log.Error("Some error occcured while sending email", this);
}
}
catch (Exception ex)
{
Sitecore.Diagnostics.Log.Error(ex.Message.ToString(), this);
}
}
#region SendEmail function
public static bool SendEmail(string To, string From, string Message)
{
bool result = true;
try
{
MailMessage mailMsg = new MailMessage();
// mailaddress of sender
MailAddress mailFrom = new MailAddress(From);
mailMsg.From = mailFrom;
// mail addresses for recipients
try
{
MailAddress mailTo = new MailAddress(To);
mailMsg.To.Add(mailTo);
}
catch
{
}
mailMsg.Body = Message;
mailMsg.IsBodyHtml = true;
var smtp = new SmtpClient(Sitecore.Configuration.Settings.MailServer, Sitecore.Configuration.Settings.MailServerPort);
smtp.Credentials = new System.Net.NetworkCredential("example@gmail.com", "password");
smtp.EnableSsl = true;
smtp.Send(mailMsg);
}
catch
{
result = false;
}
return result;
}
#endregion
public void Submit(Sitecore.Data.ID formid, AdaptedResultList fields)
{
Execute(formid, fields);
}
#region IOnLoad Members
public void OnLoad(bool isPostback, RenderFormArgs args)
{
}
#endregion