VS.NET 2010 (and above) Users Click Here   

HOMECONTACT PRODUCTS DOWNLOADS PURCHASE TESTIMONIALS FORUMS COMPANY CONTACT
Home
Products
Downloads
Purchase
Licensing
Licensing FAQ
Software Updates
Support Forums
Testimonials
Feature Requests
Guarantee
About Us
Contact Us
Hosting Companies
Privacy Policy
   
Shopping Cart


Search

aspNetPOP3 and aspNetEmail: Creating an email "Proxy" to process and resend email

by Dave 27. September 2011 13:44

Ian (on the forums) had a question about how to download email from a POP3 server, process it using his own custom rules, and then resending it.

The trick to resending it, is that he wanted to the original email to be resent and unmodified. This is a little different than the usual request. Usually, developers need to modify the original email in some fashion, rebuild it, and resend it.

In this example, Ian wanted to resend the email, as if it's never been sent. It needs to dynamically determine who to send it to, and forward it on. This makes his application work like an email proxy of sorts.

Below is a code example that would get Ian started on something like this.

As always, if anyone has any questions about this, feel free to use the Contact Us page, to send any questions.

Thanks,
Dave

Here is the code

void Execute()
{
	//connect to the pop3 server
	POP3 pop = new POP3();
	pop.Server = "mail.blah.com";
	pop.Username = "dave@blah.com";
	pop.Password = "test";

	//enable logging
	pop.LogPath = "c:\\pop.log";

	//login
	pop.Login();

	//get the first message as text
	string content = pop.GetMessageAsText(0);

	//process the message
	Process( content );
	
	ResendAsOriginal( content );

	//if we want to delete the message, uncomment the following lines
	//pop.Delete(0);
	//pop.CommitDeletes();

	//disconnect
	pop.Disconnect();
}

void Process( string emailContent )
{
	//create the MimeMessage
	MimeMessage m = MimeMessage.ParseString( emailContent );

	//do whatever we need to with the extracted data
	if( m.Subject  != null )
	{
		string subject = m.Subject.Value;
	}
}

void ResendAsOriginal( string emailContent )
{
	//create the EmailMessage object
	EmailMessage msg = new EmailMessage();

	//set the server
	msg.Server = "192.168.1.106";

	//set the TO and FROM values
	//these may need to be dynamic, and depend up on the
	//value of emailContent
	//for this example, they are hard coded

	msg.To = "CustomerService@blah.com";
	msg.FromAddress = "proxy@myserver.com";
	msg.SmtpData = emailContent;

	msg.Send();
}


aspNetEmail: Determining the Progress of the Email Sending Processes

by Dave 1. September 2011 07:02

I recently had a request on how to create a progress bar for sending an email with aspNetEmail. (thanks John!).

To do this, you need to tie into the EmailMessage  BeforeSocketSend event. This event is raised just before aspNetEmail sends the byte array of data to the underlying TCP/IP socket.

Because the email message contents are sent during the DATA command of the SMTP session, we want to wait until that section of the SMTP session takes place. Once we are in the DATA command, we can start our progress indicator. In the below example, we simply write out the current status of sending the email to a Console application.

private bool inDataEnd = false;
private double totalLength= 0.0;
private double totalSent = 0.0;
void ProgressUpdateExample()
{
	EmailMessage msg = new EmailMessage( "127.0.0.1");
	msg.From = "me@mycompany.com";
	msg.To = "you@yourcompany.com";
	msg.Subject = "large email";
	msg.Body = "this email will have a large attachment.";

	//load a large file
	FileStream fs = File.OpenRead( "c:\\temp\\largefile.jpg");
	Attachment a= new Attachment(fs, "largefile.jpg");

	msg.AddAttachment(a );

	//(Not required, but set for this example) 
//Set a socket buffer length. //this will lower the memory footprint, but increase cpu usage msg.SocketBufferLength = 2048; //wire up the BeforeSmtpSend envent msg.BeforeSmtpSend += new BeforeSmtpSendEventHandler ( OnBeforeSmtpSend ); //wire up the BeforeSocketSend event msg.BeforeSocketSend += new BeforeSocketSendEventHandler( OnBeforeSocketSend ); totalLength = (double)msg.ToString().Length; msg.Send(); } void OnBeforeSmtpSend( object sender, BeforeSmtpSendEventArgs e ) { if( e.SmtpState == SmtpState.DataEnd ) { inDataEnd = true; } else { inDataEnd = false; } } void OnBeforeSocketSend( object sender, BeforeSocketSendEventArgs e ) { if( inDataEnd ) { totalSent += (double)e.Size; double pctDone = totalSent/totalLength; Console.WriteLine( pctDone.ToString("0.00% Done")); } }


As always, if anyone has any questions or feature requests, please feel free to contact us using the Contact Us form.

Thanks,
Dave Wanta

 

aspNetEmail Supports Amazon Simple Email Service

by Dave 2. April 2011 13:33

aspNetEmail now supports the recently launched Amazon Simple Email Service.

Amazon Simple Email Service (Amazon SES) is a highly scalable and cost-effective bulk and transactional email-sending service for businesses and developers. Amazon SES eliminates the complexity and expense of building an in-house email solution or licensing, installing, and operating a third-party email service.

You can read more about the service here:
http://aws.amazon.com/ses/

Once you have signed up for the service, you will receive 2 keys from Amazon. The are an Access Key and a Secret Key.

The Access Key identifies who you are, when you make a web request to the amazon SES.

The Secret key is used to sign your request, to verify your identity.

Once you have these 2 keys, you need to first verify an email address you can used as a sender and a recipient of email.  Here is some code on how to do this:

[C#]

//create the Simple Email Service object
Ses ses =new Ses();

//create an EmailMessage object
EmailMessage msg = new EmailMessage();		

//enable logging for any troubleshooting purposes
msg.LogPath = "c:\\temp\\email.log";
msg.Logging = true;

ses.EmailMessage = msg;

//a method that fetches the Aws secret key
//the secret key will look something like BtasdfuKAEWasdfs701j2DLDFM
ses.SecretKey = AwsSecretKey();

//a method that fetches the Aws access key. 
//The access key will look something like AKIUOASDFU82PT36BA
ses.AccessKey = AwsAccessKey();

//Verify an email address
SesResponse  resp = ses.VerifyEmailAddress("test@example.com");

if( resp.ErrorString != null )
{	
	//an error occurred, write out the error message 
	Response.Write( HttpUtility.HtmlEncode( resp.ErrorString ));
}
else
{
	//Success
	//Write out the result string from Amazon
	Response.Write( HttpUtility.HtmlEncode(resp.ResultString ));			
}

[VB.NET]

'create the Simple Email Service object
Dim ses As New Ses()

'create an EmailMessage object
Dim msg As New EmailMessage()

'enable logging for any troubleshooting purposes
msg.LogPath = "c:\temp\email.log"
msg.Logging = True

ses.EmailMessage = msg

'a method that fetches the Aws secret key
'the secret key will look something like BtasdfuKAEWasdfs701j2DLDFM
ses.SecretKey = AwsSecretKey()

'a method that fetches the Aws access key. 
'The access key will look something like AKIUOASDFU82PT36BA
ses.AccessKey = AwsAccessKey()

'Verify an email address
Dim resp As SesResponse = ses.VerifyEmailAddress("test@example.com")

If Not (resp.ErrorString Is Nothing) Then
   'an error occurred, write out the error message 
   Response.Write(HttpUtility.HtmlEncode(resp.ErrorString))
Else
   'Success
   'Write out the result string from Amazon
   Response.Write(HttpUtility.HtmlEncode(resp.ResultString))
End If

Once you have verified your email address, you will receive an email from Amazon, containing a verification link. This link simply verifies you have access to the account you are validating. You can also verify additional email addresses.

Once you have the email addresses verified, you can now start sending email.

Below is a code example that demonstrates this.

[C#]

//create the Simple Email Service object
Ses ses =new Ses();

//create an EmailMessage object
EmailMessage msg = new EmailMessage();		

//enable logging for any troubleshooting purposes
msg.LogPath = "c:\\temp\\email.log";
msg.Logging = true;

//set the FROM and TO addresses
msg.From = "me@example.com";
msg.AddTo("you@example.com" );

//various other properties
msg.Body = "this is an amazon test";		
msg.Subject = "amazon test";

ses.EmailMessage = msg;

//a method that fetches the Aws secret key
//the secret key will look something like BtasdfuKAEWasdfs701j2DLDFM
ses.SecretKey = AwsSecretKey();

//a method that fetches the Aws access key. 
//The access key will look something like AKIUOASDFU82PT36BA
ses.AccessKey = AwsAccessKey();

//Send the Parent EmailMessage
SesResponse  resp = ses.SendWithResponse();

if( resp.ErrorString != null )
{	
	//an error occurred, write out the error message 
	Response.Write( HttpUtility.HtmlEncode( resp.ErrorString ));
}
else
{
	//Success
	//Write out the result string from Amazon
	Response.Write( HttpUtility.HtmlEncode(resp.ResultString ));			
}

[VB.NET]

'create the Simple Email Service object
Dim ses As New Ses()

'create an EmailMessage object
Dim msg As New EmailMessage()

'enable logging for any troubleshooting purposes
msg.LogPath = "c:\temp\email.log"
msg.Logging = True

'set the FROM and TO addresses
msg.From = "me@example.com"
msg.AddTo("you@example.com" )

'various other properties
msg.Body = "this is an amazon test"		
msg.Subject = "amazon test"

ses.EmailMessage = msg

'a method that fetches the Aws secret key
'the secret key will look something like BtasdfuKAEWasdfs701j2DLDFM
ses.SecretKey = AwsSecretKey()

'a method that fetches the Aws access key. 
'The access key will look something like AKIUOASDFU82PT36BA
ses.AccessKey = AwsAccessKey()

'Send the Parent EmailMessage
Dim resp As SesResponse = ses.SendWithResponse()

If Not (resp.ErrorString Is Nothing) Then
   'an error occurred, write out the error message 
   Response.Write(HttpUtility.HtmlEncode(resp.ErrorString))
Else
   'Success
   'Write out the result string from Amazon
   Response.Write(HttpUtility.HtmlEncode(resp.ResultString))
End If

That's all there is too it. Currently this functionality is in Beta of the EmailMessage object, but it will be in production mode in Version 4.0 of aspNetEmail. If you would like a beta version of this, feel free to contact us, using the Contact Us page, and request the Amazon Ses beta.

As always, if you have any questions, comments, or feedback, let me know.

Thanks!
Dave

aspNetEmail supports Amazon SES

by Dave 31. March 2011 08:08

aspNetEmail now supports Amazon Simple Email Service (SES). This latest update is still in beta. If you would like a beta to test, feel free to contact us using the Contact Us page and request the aspNetEmail update.  Be sure to specify you want the beta version that supports Amazon SES.

When beta testing has been completed to satisfaction, the functionality will be rolled into the production release of aspNetEmail.

If anyone has any questions, feel free to contact me, again, using the Contact Us page.

Thank you,
Dave Wanta

aspNetEmail: Adding Email Functionality to SQL Server with aspNetEmail

by Dave 6. March 2011 00:17

The following steps can be taken to use aspNetEmail from inside of SQL Server.

1)Make sure database Trustworth is set to on. This is found in the database properties. To set it call:

ALTER DATABASE "database name" SET TRUSTWORTHY ON;.

Here is a real example:

ALTER DATABASE AdventureWorks SET TRUSTWORTHY ON;.

2) Because aspNetEmail depends upon System.Web, you will need to set a reference to it in SQL Server.
This can be done by executing:

CREATE ASSEMBLY SystemWeb from 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.dll'
with permission_set = unsafe
GO

Be sure the path to the System.Web.dll matches the path on your server machine.

3)To  import aspNetEmail into SQL server, expand the Programmability --> Assemblies folder (under your Database name).
Right-click the Assemblies folder, and select "New Assembly"
For perssion set, select "unrestricted"
For path, browse to the aspNetEmail filesystem location. By default, it is located under c:\program files\advancedintellect\aspNetEmail\
Set the permission set to Unrestricted

4)Verify your SQL Server is CLR enabled by running the following T-SQL statement:

sp_configure 'clr enabled',1

followed by either a server stop/re-start, or executing:

reconfigure

5)Open Visual Studio, and create a SQL database project

6)In the Visual Studio Solution Explorer pane,  right-click References, and select "Add Reference".

7)The Add References dialog box appears.

8)Under the SQL Server tab, select aspNetEmail.

9)Choose Project->Add User Defined Function, and name the .cs file anything you like, such as "EmailHelper.cs".

Add the SendEmail() method so your code looks something like:

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlString SendEmail()
    {
        SqlString result = new SqlString("success");

        EmailMessage.LoadLicenseFile("c:\\aspNetEmail.xml.lic");
   
        EmailMessage msg = new EmailMessage("127.0.0.1");
        msg.From = "me@example.com";
        msg.To = "you@example.com";
        msg.Subject = "My test email from sql server set at: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm");
        msg.Body = "put the contents of your email body here...";
        msg.Send();

        return result;
    }

};

Once that is complete, you can now use your new function like any other User Defined T-SQL function.  For example,

select dbo.SendEmail()

This method can easily be modified to accept various parameters (such as recipients) to send emails to different people.


 

Sending Email from different local IPs

by Dave 4. March 2011 06:05

I recently had a question about aspNetEmail (thanks Clay!).  He wanted to know how he could use aspNetEmail to choose different local IPs for sending emails.

A little background
aspNetEmail creates it's own TCP/IP sockets to send email. What it does, is open a local TCP/IP socket, and establish a remote endpoint with the server specified by the .Server property.

When that local TCP/IP socket is created, aspNetEmail lets the .NET framework randomly select a local IP and Port to use. We can override the behavior by using the .LocalEndpoint property found on the EmailMessage object.

Here is a short but complete code example that demonstrates this functionality.


C#

EmailMessage msg = new EmailMessage( "127.0.0.1" );

msg.FromAddress = "me@mycompany.com";
msg.To = "you@yourcompany.com";

msg.Subject = "Your Order Confirmation Number is 12345";
msg.Body = "put our body contents here...";

//local endpoint -- this opens a local TCP/IP socket on IP 192.168.1.18 and port 5555
msg.LocalEndPoint = new IPEndPoint( IPAddress.Parse( "192.168.1.18" ), 5555 );

//if we only know the IP we want the socket open on, and not the port, we can 
//pass in 0 for the port, and the underlying OS will randomly pick an open port
//for example
//msg.LocalEndPoint = new IPEndPoint( IPAddress.Parse( "192.168.1.18" ), 0);

//any logging (not reqired) for troubleshooting
msg.LogPath = "c:\\temp\\email.log";
msg.Logging = true;

msg.Send();



VB.NET

Dim msg As New EmailMessage("127.0.0.1")

msg.FromAddress = "me@mycompany.com"
msg.To = "you@yourcompany.com"

msg.Subject = "Your Order Confirmation Number is 12345"
msg.Body = "put our body contents here..."

'local endpoint -- this opens a local TCP/IP socket on IP 192.168.1.18 and port 5555
msg.LocalEndPoint = New IPEndPoint(IPAddress.Parse("192.168.1.18"), 5555)

'if we only know the IP we want the socket open on, and not the port, we can 
'pass in 0 for the port, and the underlying OS will randomly pick an open port
'for example
'msg.LocalEndPoint = New IPEndPoint(IPAddress.Parse("192.168.1.18"), 0)

'any logging (not reqired) for troubleshooting
msg.LogPath = "c:\temp\email.log"
msg.Logging = True

msg.Send()

As always, if anyone has any questions, feel free to contact me over at Contact Us

Thanks!
Dave Wanta

 

Sending Email through Gmail using aspNetEmail

by Dave 2. March 2011 03:42

aspNetEmail can easily send email through Gmail. To do this, you must do the following:

a) Download the AdvancedIntellect.Ssl.dll from http://www.advancedintellect.com/download.aspx
b) Use aspNetEmail over SSL at port 587 to connect and send.

Lets discuss this below.

Download the AdvancedIntellect.Ssl.dll
To send email through Gmail, you need to do this over SSL. The AdvancedIntellect.Ssl.dll provides this functionality. It is a plugin that can be used with aspNetEmail.
You can download the dll from http://www.advancedintellect.com/download.aspx

Use aspNetEmail over SSL at port 587 to connect.
Once you've downloaded the dll, you can integrate it into your project.

If you are using VS.NET, import the dll into your application, and set a reference to it.

If you are not using VS.NET, you should be able to just copy the dll to your /bin directory.

Below is a simple code example that demonstrates sending the email through gmail.


C#

EmailMessage msg = new EmailMessage();

string userAccount = "MyAccount@gmail.com";
string password = "MyPassword";

//some basic properties
msg.Server = "smtp.gmail.com";
msg.Port = 587;
msg.Username = userAccount;
msg.Password = password;

msg.FromAddress = userAccount;
msg.To= "You@yourcompany.com";
msg.Subject = "This is my test email through gmail.";
msg.Body = "Put the body contents here...";

//any logging (not reqired) for troubleshooting
msg.LogPath = "c:\\temp\\email.log";
msg.Logging = true;

//create the ssl socket
AdvancedIntellect.Ssl.SslSocket ssl = new AdvancedIntellect.Ssl.SslSocket();
msg.LoadSslSocket( ssl, false);

//logging on the ssl socket
ssl.Logging = true;
ssl.LogPath = "c:\\ssl.log";

msg.Send();


VB.NET

Dim msg As New EmailMessage()

Dim userAccount As String = "MyAccount@gmail.com"
Dim password As String = "MyPassword"

'some basic properties
msg.Server = "smtp.gmail.com"
msg.Port = 587
msg.Username = userAccount
msg.Password = password

msg.FromAddress = userAccount
msg.To = "You@yourcompany.com"
msg.Subject = "This is my test email through gmail."
msg.Body = "Put the body contents here..."

'any logging (not reqired) for troubleshooting
msg.LogPath = "c:\temp\email.log"
msg.Logging = True

'create the ssl socket
Dim ssl As New AdvancedIntellect.Ssl.SslSocket()
msg.LoadSslSocket(ssl, False)

'logging on the ssl socket
ssl.Logging = True
ssl.LogPath = "c:\ssl.log"

msg.Send()

As always, if anyone has any questions, feel free to contact me over at the Contact Us web page.


Thanks,
Dave Wanta

 

iCalendar as an Email Body

by Dave 14. October 2010 01:58

 Recently I had a request about sending an iCalendar (Meeting Request) object, as the email body itself, rather than as an attachment.(Thanks Paras!)

Background
iCalendars are special attachments that can be used to represent Meeting Requests or Appointments. By default, most mail systems like to have the iCalendar  object as an alternative body. In fact, that is how I wrote aspNetEmail to work. When you can create and add an iCalendar to the EmailMessage object, under the covers, aspNetEmail actually adds it to the internal body parts collection.

Below are 3 code examples. One example demonstrates creating a standard iCalendar enabled  email.  The 2nd example demonstrates creating email that has the iCalendar as the body. The 3rd example offers a combination of the 2.

All 3 of these examples use the following helper method called CreateiCal(…)

Create iCal creates a very simple iCalendar object, that has a meeting set tomorrow at 10am.

public iCalendar CreateiCal()
{
	iCalendar iCal = new iCalendar(); 
	iCal.ContentTransferEncoding = MailEncoding.Bit7;

	//create an start and end date, tomorrow at 10am, for 1 hr.
	DateTime tomorrow = DateTime.Now.AddDays(1);
	DateTime start = new DateTime( tomorrow.Year, tomorrow.Month, tomorrow.Day, 10,0,0);
	DateTime end = start.AddHours( 1 );

	//set some basic properties
	iCal.Event.Summary.Text = "this is a test ical"; 
	iCal.Event.Location.Text = "100 main conf room"; 
	iCal.Event.DateStart.Date = start; 
	iCal.Event.DateEnd.Date = end; 

	iCal.TimeZone.Format = TimeZoneFormat.ConvertToUTC;

	return iCal;
}

Example 1
This example demonstrates how to create a standard iCalendar enabled email. This code example will create the iCalender object, and add it to the EmailMessage object. Internally, aspNetEmail actually adds the iCalender to the internal body parts collection. The resulting email will actually have 3 body parts:

a)A Plain Text body part
b)A Html Body Part
c)An iCalendar Body Part

Here is a code example that demonstrates this behavior, along with a screenshot of the resulting email.

public void NormaliCalendar()
{
	//create a normal EmailMessage object
	//set some basic properties
	EmailMessage msg = new EmailMessage( "127.0.0.1" );
	msg.From = "me@example.com";
	msg.To = "you@example.com";
	msg.Subject = "ical test";

	//create the iCalendar object
	iCalendar iCal = CreateiCal(); 

	//add the iCalendar to the EmailMessage object
	msg.AddCalendar( iCal );

	//send it
	//msg.Send();
}

Notice that in that screenshot, we can have a nicely formatted, easily readable body. By default, aspNetEmail will create this from the properties of the iCalendar. However, the developer can over ride this behavior, and create their own friendly body.

Example 2
Some mail systems don't like to have a 3rd body part. This is typically a smaller subset, has a specialized situation. Instead, these mail systems like to have the entire body of the email actually be the iCalendar. The limitation of this is that some mail systems don't know how to interpret the email message.  This may or may not affect your situation. If you need to have the iCalendar object be the email body, the following code example demonstrates this behavior. Also, found below, is a screenshot of an email that doesn't know how to render this type of format.

public void iCalAsBody()
{
	//create a normal EmailMessage object
	//set some basic properties
	EmailMessage msg = new EmailMessage( "127.0.0.1" );
	msg.From = "me@example.com";
	msg.To = "you@example.com";
	msg.Subject = "ical test";

	//create the iCalendar object
	iCalendar iCal = CreateiCal(); 

	//set the body of the EmailMessage object itself.
	msg.ContentType = "text/Calendar;\r\n\tMethod=\"REQUEST\";";
	msg.Body = 	iCal.ToString( iCalendarType.iCal );

	//send it
	//msg.Send();

}

Notice that in this screenshot, the email is not easily reable. Also, this iCalendar appears to be missing. This is because the email client (Outlook Express in this example) doesn't know how to render an email, where the body is an iCalender.

Example 3
The 3rd example attempts to offer a combination of both Example 1 and Example 2. By adding a "name" parameter to the Content-Type value, we can get some mail clients to alternatively render the body of the email as an attachment. There really isn't an attachment, but the mail client thinks there is. This allows some mail clients to at least add the iCalendar to their calendaring system.

Below is a code example that demonstrates this, along with a screenshot of the resulting email.

public void iCalAsBodyAndAttachment()
{
	//create a normal EmailMessage object
	//set some basic properties
	EmailMessage msg = new EmailMessage( "127.0.0.1" );
	msg.From = "me@example.com";
	msg.To = "you@example.com";
	msg.Subject = "ical test";

	//create the iCalendar object
	iCalendar iCal = CreateiCal(); 

	//set the body of the EmailMessage object itself.
	//however, the additional Name parameter tricks the 
	//mail client into thinking there is an attachment
	msg.ContentType = "text/Calendar;\r\n\tMethod=\"REQUEST\";\r\n\tName=\"meeting.ics\"";
	msg.Body = 	iCal.ToString( iCalendarType.iCal );
	//send it
	//msg.Send();

}

 

Although this email isn't as pretty, by adding the "Name" parameter, it allows the mail client to present the user with an iCal that can be used.

As always, if anyone has any questions, feel free to contact me.

Thanks!
Dave Wanta

Using the ReversePath property

by Dave 13. October 2010 15:05

Today I received a request (Thanks Suraj!) about using a different email address during the SMTP process than what is seen in the email. Is this possible?

The short answer is "yes"!

aspNetEmail exposes a property called the ReversePath property. By default, this value is the FromAddress value.  The ReversePath value will be used during the SMTP process. Specifically is the value of the "MAIL FROM" command.

This is useful, because some mail servers will only allow a specific email address to be used, but you may want a different FROM value in the email seen by the end user. 

Here is a specific example.  Suppose you have a CRM application hosted by a provider that has a locked down mail server. The hosting provider may only allow email to be relayed through their mail server using a single MAIL FROM address. However, the CRM application needs to send out email from different users.  Using the ReversePath property allows this to happen.  The ReversePath property will be using as the MAIL FROM value, while the FromAddress value will be the actual value seen in the mail client. An added bonus to doing this is that all human replies can go back to the FromAddress mailbox, while NDR bounces can go back to the ReversePath mailbox.   You can then use something like ListNanny to process all of the bounces found in the ReversePath mailbox, without cluttering up someone's (FromAddress) personal mailbox.

As always, if you have any more questions about the ReversePath property, and how it works, please let me know.

Thanks!
Dave Wanta

DomainKeys and DKIM with aspNetEmail and SmarterMail

by Dave 5. October 2010 08:13

Note:This code example will only be valid until aspNetEmail v4.0 releases. Once it releases, the aspNetDkim will no longer be needed, as the DKIM and DomainKeys signing functionality will be baked into aspNetEmail.

I recently had a customer (thanks Noah!) email me and ask how to perform a DomainKeys and/or DKIM  signed mail merge against the SmarterMail queue directory.

Great Question!

It turns out its relatively easy. What you will need to do, is:

a)Tie into aspNetEmail's new Queuing namespace, that has a new SmarterMail class.
b)Tie into the new RenderEmailContents event
c)In that event, sign the message, and return the signed contents to be written to the queue folder.

Here is the code example that demonstrates this functionality.

 

private void SmarterMailTest()
{
	
	//create the EmailMessage object, and set some basic properties
	EmailMessage msg = new EmailMessage();
	msg.From = "me@mycompany.com";
	msg.AddTo( "##EmailAddress##" );
	msg.Subject = "Order Confirmation";

	//a very simple body for testing purposes
	msg.Body = "Hi ##FirstName## ##LastName##, here is your order total ##Amount##";
	
	//add the render event, so we can sign the message
	msg.RenderEmailContents += new RenderEmailContentsEventHandler( SignForSmartermail );

	//set the SmarterMail queuing			
	aspNetEmail.Queuing.SmarterMail sm = new aspNetEmail.Queuing.SmarterMail( msg );
	sm.SpoolDirectory = "c:\\temp\\";

	//GetDataTable() is a method that fetches our data, and returns a DataTable object
	DataTable dt = GetDataTable();
	sm.SendMailMerge( dt );

}
private void SignForSmartermail( object sender, RenderEmailContentsEventArgs e )
{
	string contents = e.Contents;

	//sign the contents with DomainKeys
	contents = SignDKForSmartermail( contents );
	
	//we can also sign with Dkim
	//contents = SignDkimForSmartermail( contents );

	//reset the contents
	e.Contents = contents;


}


private string SignDKForSmartermail( string contents )
{
	DomainKeys dkeys = new DomainKeys( contents );


	//parse the private rsa key that was generated by openSSL.exe
	
	//we can get it from the file
	dkeys.DKCertificate = DKCertificate.ParsePemFile( "testing\\rsa.private" );

	dkeys.Canonicalization = CanonicalizationType.Simple;

	//the dns record selector
	dkeys.Selector = "testing";
	
	//sign the email contents
	string signedContents = dkeys.SignMail();

	return signedContents;

}


private string SignDkimForSmartermail( string contents )
{
	Dkim dk = new Dkim( contents );
	
	dk.Identity = "@mycompany.com";

	//parse the private rsa key that was generated by openSSL.exe
	//we can get it from the file
	dk.DKCertificate = DKCertificate.ParsePemFile( "testing\\rsa.private" );

	dk.SendingDomain = "mycompany.com";

	//the dkim dns record selector (based upon our DNS server settings
	dk.Selector = "testing";

	dk.HeaderNamesOption = HeaderNamesOptions.AllMessageHeaders;

	//sign the email contents
	string signedContents = dk.SignMail();

	return signedContents;
}

As always, if anyone has any questions, comments, or feature requests, feel free to let me know.

Thanks!
Dave Wanta

 

 

Testimonial

I really enjoy using your product and recommend it to anyone asking about an email solution! "

D. Humphrey | loanproposals.com

Read more testimonials
ListNanny aspNetDNS aspNetEmail aspNetPOP3 aspNetMX IPMuncher aspNetMIME aspNetPING aspNetTraceRoute aspNetIMAP aspNetMHT