Sending Email From Custom Code

Usually in ASP.NET applications people store the smtp settings in the <system.Net><mailSettings> section. In mojoPortal, we use custom settings in the <appSettings section instead. This allows you to store them in user.config rather than Web.config so that you don't have to worry about losing those settings when you upgrade to new versions and get the new Web.config file. Also, with mojoPortal it is possible to host multiple sites in the same installation, and you may want to use different smtp settings for each site, and this would not be possible if you use the settings from <system.Net><mailSettings> since those are global to the whole installation. We have an extra config setting that allows you to store the smtp settings as part of Site Settings so that you can specify different settings for each site. The only down side of our approach is that it means code that sends email needs to read the smtp settings from the custom location and assign them to the SmtpClient, whereas the settings from <system.Net><mailSettings> would be used automatically. However, we have some helper methods built into mojoPortal to make it easier so you don't have to write your own code to configure the smtp settings. 

First, if your code is in a custom project you need to add a reference to the mojoPortal.Net project. Then you can use our Email class to send email. A simple example is shown below, but there are additional overloads that provide support for more advanced things like sending attachments.

using mojoPortal.Net;


SmtpSettings smtpSettings = SiteUtils.GetSmtpSettings();

string from = "foo@foo.com";
string to = "me@foo.com";
string cc = string.Empty;
string bcc = string.Empty;
string subject = "Hello There";
string message = "Hows it going?";
bool isHtml = false;
string priority = "Normal";

Email.SendEmail(
smtpSettings,
from,
to,
cc,
bcc,
subject,
message,
isHtml,
priority);

Sending Email with a Task

There is also an alternate way to send email using a task that will send it from a background thread. The following code snippet shows an example:

using mojoPortal.Net;
using mojoPortal.Web;

SmtpSettings smtpSettings = SiteUtils.GetSmtpSettings();
foreach (string email in myEmails)
{
   EmailMessageTask messageTask = new EmailMessageTask(smtpSettings);

   messageTask.EmailFrom = siteSettings.DefaultEmailFromAddress;
   messageTask.EmailTo = email;
   messageTask.Subject = mySubject;
   messageTask.TextBody = myMessage;
   messageTask.SiteGuid = siteSettings.SiteGuid;
   messageTask.QueueTask();
}
WebTaskManager.StartOrResumeTasks();

See Also:

Created by Joe Audette on Jun 14, 2012
Last Modified by Joe Audette on Jun 14, 2012