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;

var smtpSettings = SiteUtils.GetSmtpSettings();
var from = "foo@foo.com";
var to = "me@foo.com";
var cc = string.Empty;
var bcc = string.Empty;
var subject = "Hello There";
var message = "Hows it going?";
var isHtml = false;
var 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;

var smtpSettings = SiteUtils.GetSmtpSettings();

foreach (var email in myEmails)
{
	var messageTask = new EmailMessageTask(smtpSettings)
	{
		EmailFrom = siteSettings.DefaultEmailFromAddress,
		EmailTo = email,
		Subject = mySubject,
		TextBody = myMessage,
		SiteGuid = siteSettings.SiteGuid,
	};

	messageTask.QueueTask();
}

WebTaskManager.StartOrResumeTasks();

See Also:

Last Modified by Elijah Fowler on Jul 11, 2022