Вы находитесь на странице: 1из 41

C# sample source code showing how to create a bounced mail handler.

private void button1_Click(object sender, System.EventArgs e)


{
// The Chilkat Bounce component is used to classify an email as
// one of several types of automated replies such as bounced
// email messages, virus warnings, out-of-office replies, etc.
// To read email from a POP3 server, the Chilkat Mail component
// (licensed separately) is used.

Chilkat.MailMan mailman = new Chilkat.MailMan();


mailman.UnlockComponent("MailUnlockCode");
mailman.MailHost = "mail.chilkatsoft.com";
mailman.PopUsername = "login";
mailman.PopPassword = "password";

Chilkat.Bounce bounce = new Chilkat.Bounce();


bool success = bounce.UnlockComponent("BounceUnlockCode");
if (!success)
{
textBox1.Text = bounce.LastErrorText;
return;
}

// Read email from the POP3 server.


Chilkat.EmailBundle bundle;
bundle = mailman.CopyMail();
if (bundle != null)
{
// Loop over each email...
Chilkat.Email email;
int i;
bool success;
for (i=0; i<bundle.MessageCount; i++)
{
email = bundle.GetEmail(i);

// See if this is a bounced email.


// This sets the properties of the Bounce object
success = bounce.ExamineEmail(email);
if (!success)
listBox1.Items.Add("Failed to classify email");
else if (bounce.BounceType == 1)
// Hard bounce, log the email address
listBox1.Items.Add("Hard Bounce: " + bounce.BounceAddress);
else if (bounce.BounceType == 2)
// Soft bounce, log the email address
listBox1.Items.Add("Soft Bounce: " + bounce.BounceAddress);
else if (bounce.BounceType == 3)
// General bounce, no email address available.
listBox1.Items.Add("General Bounce: No email address");
else if (bounce.BounceType == 4)
// General bounce, log the email address
listBox1.Items.Add("General Bounce: " + bounce.BounceAddress);
else if (bounce.BounceType == 5)
// Mail blocked, log the email address
listBox1.Items.Add("Mail Blocked: " + bounce.BounceAddress);
else if (bounce.BounceType == 6)
// Auto-reply, log the email address
listBox1.Items.Add("Auto-Reply: " + bounce.BounceAddress);
else if (bounce.BounceType == 7)
// Transient (recoverable) Failure, log the email address
listBox1.Items.Add("Transient Failure: " + bounce.BounceAddress);
else if (bounce.BounceType == 8)
// Subscribe request, log the email address
listBox1.Items.Add("Subscribe Request: " + bounce.BounceAddress);
else if (bounce.BounceType == 9)
// Unsubscribe Request, log the email address
listBox1.Items.Add("Unsubscribe Request: " + bounce.BounceAddress);
else if (bounce.BounceType == 10)
// Virus Notification, log the email address
listBox1.Items.Add("Virus Notification: " + bounce.BounceAddress);
else if (bounce.BounceType == 11)
// Suspected bounce.
// This should be rare. It indicates that the Bounce
// component found strong evidence that this is a bounced
// email, but couldn//t quite recognize everything it
// needed to be 100% sure. Feel free to notify
// support@chilkatsoft.com regarding emails having this
// bounce type.
listBox1.Items.Add("Suspected Bounce!");

email = null;
}
bundle = null;
}
mailman = null;
}
}
utf-8 to Shift-JIS Conversion
Download C# Project Files and Source Code
C# source code example showing how to convert utf-8 text to the Shift-JIS character encoding.
private void button1_Click(object sender, System.EventArgs e)
{
Chilkat.Charset cc = new Chilkat.Charset();
cc.UnlockComponent("Anything begins 30-day trial");

// Read utf-8 text from a file.


System.IO.FileInfo fInfo = new System.IO.FileInfo("utf8Sample.txt");
System.IO.BinaryReader br = new System.IO.BinaryReader(
System.IO.File.OpenRead("utf8Sample.txt"));
byte [] utf8Bytes = br.ReadBytes((int)fInfo.Length);
br.Close();

// Convert from utf-8 to Shift-JIS


cc.FromCharset = "utf-8";
cc.ToCharset = "shift_JIS";
byte [] shiftJisBytes = cc.ConvertData(utf8Bytes);
// Write the output file in Shift-JIS
// Write the encrypted binary file.
System.IO.BinaryWriter bw = new System.IO.BinaryWriter(
System.IO.File.Create("shiftJisSample.txt"));
bw.Write(shiftJisBytes);
bw.Close();
}
Shift-JIS to UTF-8 Conversion
Download C# Project Files and Source Code
C# source code sample program demonstrating how to convert Shift-JIS Japanese character data to utf-8.
private void button1_Click(object sender, System.EventArgs e)
{
Chilkat.Charset cc = new Chilkat.Charset();
cc.UnlockComponent("Anything begins 30-day trial");

// Read Shift-JIS text from a file.


System.IO.FileInfo fInfo = new System.IO.FileInfo("shiftJisSample.txt");
System.IO.BinaryReader br = new System.IO.BinaryReader(
System.IO.File.OpenRead("shiftJisSample.txt"));
byte [] shiftJisBytes = br.ReadBytes((int)fInfo.Length);
br.Close();

// Convert from Shift-JIS to utf-8


cc.ToCharset = "utf-8";
cc.FromCharset = "Shift_JIS";
byte [] utf8Bytes = cc.ConvertData(shiftJisBytes);

// Write the output file in Shift-JIS


System.IO.BinaryWriter bw = new System.IO.BinaryWriter(
System.IO.File.Create("utf8Sample.txt"));
bw.Write(utf8Bytes);
bw.Close();
}
Shift-JIS to URL Encoding
Converts Shift-JIS encoded character data into a URL-encoded string.
Chilkat.Crypt2 crypt2 = new Chilkat.Crypt2();
crypt2.UnlockComponent("anything for 30-day trial");
crypt2.CryptAlgorithm = "none";
crypt2.EncodingMode = "url";
crypt2.Charset = "shift-jis";

// This example loads Shift-JIS bytes from a file


// This file can be found at http://www.chilkatsoft.com/testData/shiftJisChars.txt
byte [] shiftJisBytes = crypt2.ReadFile("shiftJisChars.txt");

string urlEncoded = crypt2.EncryptBytesENC(shiftJisBytes);

MessageBox.Show(urlEncoded);

Important: The download for this example does not contain the ChilkatDotNet.dll which
must be downloaded and installed separately at http://www.chilkatsoft.com/downloads.asp.
Once installed, add a reference to the DLL in the project by following the instructions at
http://www.example-code.com/vbdotnet/step2.asp
Convert any HTML File to utf-8
C# example program to convert any HTML file to the utf-8 character encoding.
// Convert an HTML file to utf-8.
Chilkat.Charset cc = new Chilkat.Charset();
cc.UnlockComponent("anything for 30-day trial");

// The file in this example uses the windows-1256 encoding.


// To convert it to utf-8, call ConvertHtmlFile.
// The HTML META tag specifying the charset is automatically
// modified to specify utf-8, and the character data is converted.

// It is not necessary to specify the FromCharset if the encoding


// is present in the HTML, such as like this:
// <META http-equiv=Content-Type content="text/html; charset=windows-1256" >

// Therefore, these two lines of code are capable of converting


// any HTML file to utf-8, regardless of the original charset.
cc.ToCharset = "utf-8";
cc.ConvertHtmlFile("arabicNews.html", "arabicUtf8.html");

Important: The download for this example does not contain the ChilkatDotNet.dll which
must be downloaded and installed separately at http://www.chilkatsoft.com/downloads.asp.
Once installed, add a reference to the DLL in the project by following the instructions at
http://www.example-code.com/vbdotnet/step2.asp
Read CSV File
Demonstrates how to read a .csv file and access the contents.
The Chilkat CSV library/component/class is freeware. The downloads for .NET, C++, Perl, Java, Ruby, and
Python contain all of the Chilkat classes, some of which are freeware and some of which require licensing.
Download Chilkat .NET for 2.0 / 3.5 Framework
Download Chilkat .NET for 64-bit 2.0 / 3.5 Framework (x64)
Download Chilkat .NET for 1.0 / 1.1 Framework
// This example program loads a file (sample.csv)
// that contains this content:
//
// year,color,country,food
// 2001,red,France,cheese
// 2005,blue,"United States",hamburger
// 2008,green,Italy,pasta
// 1998,orange,Japan,sushi
//
// The first row contains the column names.
// This file is available at:
// http://www.chilkatsoft.com/testData/sample.csv

Chilkat.Csv csv = new Chilkat.Csv();

// Prior to loading the CSV file, indicate that the 1st row
// should be treated as column names:
csv.HasColumnNames = true;

// Load the CSV records from the file:


bool success;
success = csv.LoadFile("sample.csv");
if (success != true) {
MessageBox.Show(csv.LastErrorText);
return;
}
// Display the contents of the 3rd column (i.e. the country names)
int row;
int n;
n = csv.NumRows;
for (row = 0; row <= n - 1; row++) {
textBox1.Text += csv.GetCell(row,2) + "\r\n";
}

List Windows Local Machine Certificates


Demonstrates how to open the registry-based Local Machine certificate store on a Windows OS and list the
digital certificates.
Download Chilkat .NET for 2.0 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
// This example demonstrates how to list the certificates
// in a Windows Local Machine Certificate Store.

// This is our certificate store factory object:


Chilkat.CreateCS ccs = new Chilkat.CreateCS();
ccs.ReadOnly = true;

// Open the local machine store:


Chilkat.CertStore cs;
cs = ccs.OpenLocalSystemStore();

if (!(cs == null )) {

Chilkat.Cert cert;
int numCerts;
numCerts = cs.NumCertificates;
int i;
// Print the distinguished name of each certificate
for (i = 0; i <= numCerts - 1; i++) {
cert = cs.GetCertificate(i);
textBox1.Text += cert.SubjectDN + "\r\n";
textBox1.Refresh();
}

}
else {
MessageBox.Show(ccs.LastErrorText);
}

// The Chilkat Certificate, Certificate Store, Private Key,


// Public Key, and Key Container classes / objects are freeware.

// They are used by and included with the Chilkat Email,


// Crypt, S/MIME, and other commercial Chilkat components.

List Windows Current User Certificates


Demonstrates how to open the registry-based Current User certificate store on a Windows OS and list the digital
certificates.
Download Chilkat .NET for 2.0 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
// This example demonstrates how to list the certificates
// in the logged-on user's registry-based Current User Certificate Store.
// This is our certificate store factory object:
Chilkat.CreateCS ccs = new Chilkat.CreateCS();
ccs.ReadOnly = true;

// Open the current-user certificate store:


Chilkat.CertStore cs;
cs = ccs.OpenCurrentUserStore();

if (!(cs == null )) {

Chilkat.Cert cert;
int numCerts;
numCerts = cs.NumCertificates;
int i;
// Print the distinguished name of each certificate
for (i = 0; i <= numCerts - 1; i++) {
cert = cs.GetCertificate(i);
textBox1.Text += cert.SubjectDN + "\r\n";
textBox1.Refresh();
}

}
else {
MessageBox.Show(ccs.LastErrorText);
}

// The Chilkat Certificate, Certificate Store, Private Key,


// Public Key, and Key Container classes / objects are freeware.

// They are used by and included with the Chilkat Email,


// Crypt, S/MIME, and other commercial Chilkat components.

Export Private Key to PKCS8, PEM, DER, XML


Demonstrates how to export a digital certificate's private key to RSA PEM or DER, PKCS8 PEM or DER, or
XML.
Download Chilkat .NET for 2.0 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
Chilkat.Cert cert = new Chilkat.Cert();

// Th LoadByCommonName method searches the Windows


// Current User Certificate Store and Local Machine Certificate
// Store for a certificate whose common name (CN) matches
// the argument:
bool success;
success = cert.LoadByCommonName("Chilkat Software, Inc.");
if (success == false) {
MessageBox.Show("Failed to find certificate!");
}
else {

// Get the PrivateKey object:


Chilkat.PrivateKey pkey;

pkey = cert.ExportPrivateKey();
if (!(pkey == null )) {
// Export the private key to an RSA DER file:
pkey.SaveRsaDerFile("pkey_rsa.der");

// Export to a PKCS8 DER file:


pkey.SavePkcs8File("pkey_pkcs8.der");

// Export to an RSA PEM file:


pkey.SaveRsaPemFile("pkey_rsa.pem");

// Export to a PKCS8 PEM file:


pkey.SavePkcs8PemFile("pkey_pkcs8.pem");

// Export to XML:
pkey.SaveXmlFile("pkey.xml");

// Get PKCS8 PEM string:


textBox1.Text += "PKCS8 PEM Private Key:" + "\r\n";
textBox1.Refresh();
textBox1.Text += pkey.GetPkcs8Pem() + "\r\n";
textBox1.Refresh();

// Get RSA PEM string:


textBox1.Text += "RSA PEM Private Key:" + "\r\n";
textBox1.Refresh();
textBox1.Text += pkey.GetRsaPem() + "\r\n";
textBox1.Refresh();

}
else {
MessageBox.Show("No private key found!");
}

// The Chilkat Certificate, Certificate Store, Private Key,


// Public Key, and Key Container classes / objects are freeware.

// They are used by and included with the Chilkat Email,


// Crypt, S/MIME, and other commercial Chilkat components.
Export Public Key to RSA DER, OpenSSL DER/PEM, XML
Demonstrates how to export a digital certificate's public key to RSA DER, OpenSSL PEM or DER, or to XML
format.
Download Chilkat .NET for 2.0 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
Chilkat.Cert cert = new Chilkat.Cert();

// Th LoadByCommonName method searches the Windows


// Current User Certificate Store and Local Machine Certificate
// Store for a certificate whose common name (CN) matches
// the argument:
bool success;
success = cert.LoadByCommonName("Chilkat Software, Inc.");
if (success == false) {
MessageBox.Show("Failed to find certificate!");
}
else {

// Get the PublicKey object:


Chilkat.PublicKey pkey;

pkey = cert.ExportPublicKey();
if (!(pkey == null )) {

// Export the public key to an RSA DER file:


pkey.SaveRsaDerFile("pubkey_rsa.der");

// Export to an OpenSSL DER file:


pkey.SaveOpenSslDerFile("pubkey_openssl.der");

// Export to an OpenSSL PEM file:


pkey.SaveOpenSslPemFile("pubkey_openssl.pem");

// Export to an XML file:


pkey.SaveXmlFile("pubkey.xml");

// Get OpenSSL PEM string:


textBox1.Text += "OpenSSL PEM Public Key:" + "\r\n";
textBox1.Refresh();
textBox1.Text += pkey.GetOpenSslPem() + "\r\n";
textBox1.Refresh();

}
else {
MessageBox.Show("No public key found!");
}

// The Chilkat Certificate, Certificate Store, Private Key,


// Public Key, and Key Container classes / objects are freeware.

// They are used by and included with the Chilkat Email,


// Crypt, S/MIME, and other commercial Chilkat components.

Export Certificate to DER or PEM


Demonstrates how to export a digital certificate to PEM or DER format.
Download Chilkat .NET for 2.0 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
Chilkat.Cert cert = new Chilkat.Cert();

// Th LoadByCommonName method searches the Windows


// Current User Certificate Store and Local Machine Certificate
// Store for a certificate whose common name (CN) matches
// the argument:
bool success;
success = cert.LoadByCommonName("Chilkat Software, Inc.");
if (success == false) {
MessageBox.Show("Failed to find certificate!");
}
else {
// Export certificate to a PEM file
cert.ExportCertPemFile("cert.pem");

// Export certificate to a DER file


cert.ExportCertDerFile("cert.der");

// Export cert to a PEM string:


textBox1.Text += cert.ExportCertPem() + "\r\n";
textBox1.Refresh();

// The Chilkat Certificate, Certificate Store, Private Key,


// Public Key, and Key Container classes / objects are freeware.

// They are used by and included with the Chilkat Email,


// Crypt, S/MIME, and other commercial Chilkat components.

Use Certificate and Private Key PEM Files to Create a Digital Signature
Demonstrates how to load a digital certificate from a PEM file, load it's corresponding private key from a PEM
file, save the private key to a key container (if necessary), link the certificate to the key container, and use it to
create a digital signature.
Download Chilkat .NET for 2.0 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
Chilkat.Cert cert = new Chilkat.Cert();

// Load the cert from a PEM file;


cert.LoadFromFile("cert.pem");

Chilkat.PrivateKey pkey = new Chilkat.PrivateKey();

// Load the private key from an RSA PEM file:


pkey.LoadPemFile("pkey_rsa.pem");

bool success;

// If the "chilkat" key container does not already exist,


// we'll create it and import the private key:
Chilkat.KeyContainer container = new Chilkat.KeyContainer();
bool needPrivateKeyAccess;
needPrivateKeyAccess = true;
bool machineKeyset;
machineKeyset = false;
if (container.OpenContainer("chilkat",needPrivateKeyAccess,machineKeyset) == false) {

// We need to create the key container and import


// the private key:
success = container.CreateContainer("chilkat",machineKeyset);
if (success == true) {
bool isKeyExchangePair;
isKeyExchangePair = false;
success = container.ImportPrivateKey(pkey,isKeyExchangePair);
if (success == false) {
textBox1.Text += "Failed to import private key into key container" + "\r\n";
return;
}
}
else {
textBox1.Text += "Failed to create key container" + "\r\n";
return;
}

// At this point, the key container contains the private key.


// Link the certificate with the key container:
bool bForSigning;
bForSigning = true;
success = cert.LinkPrivateKey("chilkat",machineKeyset,bForSigning);
if (success == false) {
textBox1.Text += "Failed to link certificate with key container" + "\r\n";
return;
}

// Use Chilkat Crypt (a non-freeware component) to create


// a digital signature using the certificate w/ private key:
Chilkat.Crypt2 crypt = new Chilkat.Crypt2();

// Any string argument automatically begins the 30-day trial.

success = crypt.UnlockComponent("30-day trial");


if (success != true) {
MessageBox.Show("Crypt component unlock failed");
return;
}

// Tell the crypt component to use this cert.


crypt.SetSigningCert(cert);

// We can sign any type of file, creating a .p7s as output:


success = crypt.CreateP7S("license.rtf","license.p7s");
if (success == false) {
MessageBox.Show(crypt.LastErrorText);

return;
}

textBox1.Text += crypt.LastErrorText + "\r\n";

// Verify and restore the original file:


crypt.SetVerifyCert(cert);

success = crypt.VerifyP7S("license.rtf","license.p7s");
if (success == false) {
MessageBox.Show(crypt.LastErrorText);

return;
}

MessageBox.Show("Success!");
// The Chilkat Certificate, Certificate Store, Private Key,
// Public Key, and Key Container classes / objects are freeware.

// They are used by and included with the Chilkat Email,


// Crypt, S/MIME, and other commercial Chilkat components.

Convert Certificate from PEM to DER


Convert a PEM formatted certificate file (.cer, .crt, .pem) to DER format (.cer, .der). The Chilkat certificate
class/object is a freeware component that is included in many of the Chilkat downloads.
Download Chilkat .NET for 2.0 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
Chilkat.Cert cert = new Chilkat.Cert();

bool success;

// LoadFromFile will load either PEM and DER formatted files.


// It automatically recognizes the file format based on the
// file contents.
success = cert.LoadFromFile("chilkat.crt");
if (success != true) {
MessageBox.Show(cert.LastErrorText);
return;
}

MessageBox.Show(cert.SubjectDN);

success = cert.ExportCertDerFile("chilkat.der");
if (success != true) {
MessageBox.Show(cert.LastErrorText);
return;
}

MessageBox.Show("success!");
Export certificates and public/private keys from a PFX
Demonstrates how to export certificates and public/private keys from a PFX file.
Download Chilkat .NET for 2.0 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
bool success;
Chilkat.CertStore certStore = new Chilkat.CertStore();

// Load the PFX file into a certificate store object


string password;
password = "myPassword";
success = certStore.LoadPfxFile("chilkat.pfx",password);
if (success != true) {
MessageBox.Show(certStore.LastErrorText);
return;
}

int i;
int numCerts;
numCerts = certStore.NumCertificates;

Chilkat.Cert cert;
string fname;
for (i = 0; i <= numCerts - 1; i++) {
cert = certStore.GetCertificate(i);

textBox1.Text += cert.SubjectDN + "\r\n";


textBox1.Refresh();
textBox1.Text += "---" + "\r\n";
textBox1.Refresh();

// Save the cert in DER format:


fname = "cert" + Convert.ToString(i) + ".der";
cert.ExportCertDerFile(fname);

// Save the cert in PEM format:


fname = "cert" + Convert.ToString(i) + ".pem";
cert.ExportCertPemFile(fname);

// Does this cert have a private key?


if (cert.HasPrivateKey() == true) {

// Get the private key.


Chilkat.PrivateKey pvkey;
pvkey = cert.ExportPrivateKey();

// Save the private key to a PKCS8 DER-encoded file


fname = "pvkey" + Convert.ToString(i) + "_pkcs8.der";
pvkey.SavePkcs8File(fname);

// Save the private key to a PKCS8 PEM-encoded file


fname = "pvkey" + Convert.ToString(i) + "_pkcs8.pem";
pvkey.SavePkcs8PemFile(fname);

// Save the private key to a RSA DER-encoded file


fname = "pvkey" + Convert.ToString(i) + "_rsa.der";
pvkey.SaveRsaDerFile(fname);

// Save the private key to a RSA PEM-encoded file


fname = "pvkey" + Convert.ToString(i) + "_rsa.pem";
pvkey.SaveRsaPemFile(fname);

// Save the private key to an XML file


// This format is Chilkat-specific, but easily parsed,
// making it easy to get the modulus, exponent,
// P, Q, DP, DQ, InverseQ, and D.
fname = "pvkey" + Convert.ToString(i) + ".xml";
pvkey.SaveXmlFile(fname);

// Now get the public key and save it to various file formats:
Chilkat.PublicKey pubkey;
pubkey = cert.ExportPublicKey();

// Save to an OpenSSL DER format file:


fname = "pubkey" + Convert.ToString(i) + "_openSsl.der";
pubkey.SaveOpenSslDerFile(fname);
// Save to an OpenSSL PEM format file:
fname = "pubkey" + Convert.ToString(i) + "_openSsl.pem";
pubkey.SaveOpenSslPemFile(fname);

// Save to an RSA DER format file:


fname = "pubkey" + Convert.ToString(i) + "_rsa.der";
pubkey.SaveRsaDerFile(fname);

// Save to an XML file:


// This format is Chilkat-specific, but easily parsed,
// making it easy to get the modulus and exponent.
fname = "pubkey" + Convert.ToString(i) + ".xml";
pubkey.SaveXmlFile(fname);

// The Chilkat Certificate, Certificate Store, Private Key,


// Public Key, and Key Container classes / objects are freeware.

// They are used by and included with the Chilkat Email,


// Crypt, S/MIME, and other commercial Chilkat components.
Export Certificate and Private Key to PFX
Demonstrates how to export a digital certificate, it's private key, and potentially all certificates in the chain of
authentication to a PFX file.
Download Chilkat .NET for 2.0 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
bool success;

// This object is used to create a certificate store object.


Chilkat.CreateCS ccs = new Chilkat.CreateCS();

Chilkat.CertStore certStore;
// Open the local machine certificate store read-only.
ccs.ReadOnly = true;
certStore = ccs.OpenLocalSystemStore();

// Can we find a certificate by email address?


Chilkat.Cert cert;
cert = certStore.FindCertBySubjectE("admin@chilkatsoft.com");
if (cert == null ) {
// Open the current-user certificate store and check it instead.

textBox1.Text += "Checking current-user certificate store..." + "\r\n";


textBox1.Refresh();

certStore = ccs.OpenCurrentUserStore();

cert = certStore.FindCertBySubjectE("admin@chilkatsoft.com");
if (cert == null ) {
textBox1.Text += "Failed to find certificate!" + "\r\n";
textBox1.Refresh();
return;
}

}
// Does this certificate have a private key accessible
// to the calling process? Private keys are *not* stored
// within the certificate store. Private keys are stored
// in a key container in a Windows protected store. It
// can be one of two protected stores: the protected store for
// the current logged-in user account, or the "machine-key"
// protected store. The private key must both exist in a
// protected store, and the process must have permission to
// access it...

// You can only export to a PFX if the private key exists


// and is accessible.

if (cert.HasPrivateKey() == true) {

// Export to a PFX.
// Provide a password that will be required whenever the PFX is opened.
// Also, include all certs in the chain of authentication.
bool bIncludeChain;
bIncludeChain = true;
success = cert.ExportToPfxFile("myCert.pfx","myPassword",bIncludeChain);
if (success != true) {
textBox1.Text += cert.LastErrorText + "\r\n";
textBox1.Refresh();
}
else {
textBox1.Text += "Exported to PFX!" + "\r\n";
textBox1.Refresh();
}

}
else {
textBox1.Text += "Certificate does not have a private key available" + "\r\n";
textBox1.Refresh();
}

// The Chilkat Certificate, Certificate Store, Private Key,


// Public Key, and Key Container classes / objects are freeware.

// They are used by and included with the Chilkat Email,


// Crypt, S/MIME, and other commercial Chilkat components.

Check if Certificate Expired


How to check to see if a digital certificate is expired.
Download Chilkat .NET for 2.0 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
Chilkat.Cert cert = new Chilkat.Cert();
bool isExpired;

// The LoadByCommonName method searches the registry-based


// Windows Current User Certificate Store and Local Machine Certificate
// Store for a certificate whose common name (CN) matches
// the argument:
bool success;
success = cert.LoadByCommonName("Chilkat Software, Inc.");
if (success == false) {
MessageBox.Show("Failed to find certificate!");
}
else {

// Display the certificate's distinguished name:


textBox1.Text += cert.SubjectDN + "\r\n";

isExpired = cert.Expired;
if (isExpired == true) {
textBox1.Text += "Certificate is expired." + "\r\n";
}
else {
textBox1.Text += "Certificate is NOT expired." + "\r\n";
}

// Alternatively, load a Certificate from a .cer file.


// (Certs may also be loaded from other types of files, such as PEM, DER, PFX, etc.)
success = cert.LoadFromFile("myCert.cer");
if (success == false) {
MessageBox.Show("Failed to load certificate!");
}
else {

// Display the certificate's distinguished name:


textBox1.Text += cert.SubjectDN + "\r\n";

isExpired = cert.Expired;
if (isExpired == true) {
textBox1.Text += "Certificate is expired." + "\r\n";
}
else {
textBox1.Text += "Certificate is NOT expired." + "\r\n";
}

// The Chilkat Certificate, Certificate Store, Private Key,


// Public Key, and Key Container classes / objects are freeware.

// They are used by and included with the Chilkat Email,


// Crypt, S/MIME, and other commercial Chilkat components.

PVK to XML
Convert RSA .pvk (private key) to XML.
Download Chilkat .NET for 2.0 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
Chilkat.PrivateKey pvk = new Chilkat.PrivateKey();

bool success;

// Password is "wiggy"
success = pvk.LoadPvkFile("myKey.pvk","wiggy");
if (success == false) {
textBox1.Text += pvk.LastErrorText + "\r\n";
textBox1.Refresh();
return;
}

// Save it as XML:
success = pvk.SaveXmlFile("myKey.xml");
if (success == false) {
textBox1.Text += pvk.LastErrorText + "\r\n";
textBox1.Refresh();
return;
}
Extract Public/Private Keys and Certs from PFX into String Variables
Demonstrates how to export certificates and public/private keys from a PFX file into in-memory strings.
Download Chilkat .NET for 2.0 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
bool success;
Chilkat.CertStore certStore = new Chilkat.CertStore();

// Load the PFX file into a certificate store object


string password;
password = "*myPassword2*";
success = certStore.LoadPfxFile("chilkat.pfx",password);
if (success != true) {
MessageBox.Show(certStore.LastErrorText);
return;
}

int i;
int numCerts;
numCerts = certStore.NumCertificates;

// Loop over each certificate in the PFX.


Chilkat.Cert cert = null;
string fname;
for (i = 0; i <= numCerts - 1; i++) {

cert = certStore.GetCertificate(i);

textBox1.Text += cert.SubjectDN + "\r\n";


textBox1.Text += "---" + "\r\n";

string encodedCert;
encodedCert = cert.GetEncoded();

// This string may now be stored in a relational database string field.


// To re-create the cert, do this:
Chilkat.Cert cert2 = new Chilkat.Cert();
cert2.SetFromEncoded(encodedCert);

// Does this cert have a private key?


if (cert.HasPrivateKey() == true) {

// Get the private key.


Chilkat.PrivateKey pvkey = null;
pvkey = cert.ExportPrivateKey();
// The private key can be exported into
// a string in PKCS8, RSA PEM, or XML format:
string pemPvKey;
string pkcs8PvKey;
string xmlPvKey;

pemPvKey = pvkey.GetRsaPem();
pkcs8PvKey = pvkey.GetPkcs8Pem();
xmlPvKey = pvkey.GetXml();

textBox1.Text += pemPvKey + "\r\n";


textBox1.Text += pkcs8PvKey + "\r\n";
textBox1.Text += xmlPvKey + "\r\n";

// Any of these formatted strings may


// be stored in a relational database field.
// to restore, call LoadPem or LoadXml
// LoadPem accepts either RSA PEM or
// PKCS8 PEM:
Chilkat.PrivateKey pvKey2 = new Chilkat.PrivateKey();

pvKey2.LoadPem(pemPvKey);
pvKey2.LoadPem(pkcs8PvKey);
pvKey2.LoadXml(xmlPvKey);

// Now for the public key:


Chilkat.PublicKey pubkey = null;
pubkey = cert.ExportPublicKey();

// It can be exported to a string as OpenSSL PEM


// or XML:
string pubKeyPem;
string pubKeyXml;

pubKeyPem = pubkey.GetOpenSslPem();
pubKeyXml = pubkey.GetXml();

textBox1.Text += pubKeyPem + "\r\n";


textBox1.Text += pubKeyXml + "\r\n";

// To re-load a PublicKey object, call LoadXml


// or LoadOpenSslPem:
Chilkat.PublicKey pubKey2 = new Chilkat.PublicKey();

pubKey2.LoadOpenSslPem(pubKeyPem);
pubKey2.LoadXml(pubKeyXml);
fname = "pubkey" + Convert.ToString(i) + "_openSsl.der";
pubkey.SaveOpenSslDerFile(fname);

// The Chilkat Certificate, Certificate Store, Private Key,


// Public Key, and Key Container classes / objects are freeware.
// They are used by and included with the Chilkat Email,
// Crypt, S/MIME, and other commercial Chilkat components.

Check Certificate for Private Key


Checks to see if a certificate has its associated private key installed on the computer.
Detailed Instructions for Installing a PFX for Use by ASP / ASP.NET
Download Chilkat .NET for 2.0 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
Chilkat.Cert cert = new Chilkat.Cert();

// There are many ways of loading a Chilkat certificate object:


// 1) From a Windows registry-based certificate store.
// 2) From a PFX file.
// 3) From a DER encoded .cer file.
// 4) From a PEM file.

// The point of this example is to show how to check for the existence
// of a usable private key. This is done by calling the HasPrivateKey method.

// The LoadByCommonName method searches the registry-based


// Windows Current User Certificate Store and Local Machine Certificate
// Store for a certificate whose common name (CN) matches
// the argument:
bool success;
success = cert.LoadByCommonName("Chilkat Software, Inc.");
if (success == false) {
MessageBox.Show("Failed to find certificate!");
}
else {

// Display the certificate's distinguished name:


textBox1.Text += cert.SubjectDN + "\r\n";

bool hasPrivKey;

hasPrivKey = cert.HasPrivateKey();
if (hasPrivKey == true) {
textBox1.Text += "Certificate has a usable private key." + "\r\n";
}
else {
textBox1.Text += "Certificate does not have a private key." + "\r\n";
}

// If HasPrivateKey returns false, it's possible that the private key


// does exist, but the calling process does not have permission to access it.

// If your program is running under IIS (perhaps in a web service), you need
// rights to the private key to perform a signature, and the IIS processes
// typically runs in the default IIS Application Pool under the
// NETWORK_SERVICE ID, which has no rights.

// Grant the ID Full Control rights to the private key which is stored in
// C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\Machine Keys.
// (Perhaps lesser rights would work; you may experiment).

}
// Alternatively, load a Certificate from a .cer file.
// (Certs may also be loaded from other types of files, such as PEM, DER, PFX, etc.)
success = cert.LoadFromFile("myCert.cer");
if (success == false) {
MessageBox.Show("Failed to load certificate!");
}
else {

hasPrivKey = cert.HasPrivateKey();
if (hasPrivKey == true) {
textBox1.Text += "Certificate has a usable private key." + "\r\n";
}
else {
textBox1.Text += "Certificate does not have a private key." + "\r\n";
}

}
PFX to PEM (Certificate and Private Key Files)
Export a certificate and private key from a PFX to a pair of PEM files.
Download Chilkat .NET for 2.0 / 3.5 Framework
Download Chilkat .NET for 64-bit 2.0 / 3.5 Framework (x64)
Download Chilkat .NET for 1.0 / 1.1 Framework
bool success;
Chilkat.CertStore certStore = new Chilkat.CertStore();

// Load the PFX file into a certificate store object


string password;
password = "myPassword";
success = certStore.LoadPfxFile("chilkat.pfx",password);
if (success != true) {
MessageBox.Show(certStore.LastErrorText);
return;
}

// Find the cert to be exported by the subject:


Chilkat.Cert cert = null;
cert = certStore.FindCertBySubject("Chilkat Software, Inc.");
if (cert == null ) {
MessageBox.Show("Certificate not found.");
return;
}

// Does this cert have a private key?


if (cert.HasPrivateKey() == true) {

// Get the private key.


Chilkat.PrivateKey pvkey = null;
pvkey = cert.ExportPrivateKey();

// Export the private key to a PEM file:


success = pvkey.SaveRsaPemFile("chilkat_pkey.pem");
if (success != true) {
MessageBox.Show(pvkey.LastErrorText);
return;
}
}

// Save the cert to a PEM file:


success = cert.ExportCertPemFile("chilkat_cert.pem");
if (success != true) {
MessageBox.Show(cert.LastErrorText);
return;
}
Create PFX from PEM (Certificate and Private Key Files)
Create a PFX file from a pair of PEM files (the certificate PEM and private key PEM).
Download Chilkat .NET for 2.0 / 3.5 Framework
Download Chilkat .NET for 64-bit 2.0 / 3.5 Framework (x64)
Download Chilkat .NET for 1.0 / 1.1 Framework
bool success;

Chilkat.Cert cert = new Chilkat.Cert();

success = cert.LoadFromFile("chilkat_cert.pem");
if (success != true) {
MessageBox.Show(cert.LastErrorText);
return;
}

Chilkat.PrivateKey privkey = new Chilkat.PrivateKey();


success = privkey.LoadPemFile("chilkat_pkey.pem");
if (success != true) {
MessageBox.Show(privkey.LastErrorText);
return;
}

// Link the cert to the private key.


// Use the current logged-on user's protected key store:
bool bMachineKeyset;
bMachineKeyset = false;
// If the private key is to be used for creating signatures,
// set bForSigning = true. If the private key is to be
// used for decrypting, set bForSigning = false
bool bForSigning;
bForSigning = true;

// Select an arbitrary key container name that is unique


// to your application. Make sure it exists:
Chilkat.KeyContainer keyCont = new Chilkat.KeyContainer();
// The CreateContainer method will create the key container
// if it does not already exist, otherwise it will open it.
// (The key container is in the Windows protected store.)
success = keyCont.CreateContainer("myApp",bMachineKeyset);
if (success != true) {
MessageBox.Show(keyCont.LastErrorText);
return;
}

success = cert.LinkPrivateKey("myApp",bMachineKeyset,bForSigning);
if (success != true) {
MessageBox.Show(cert.LastErrorText);
return;
}

// Now export to a PFX:


bool bIncludeCertsInChain;
bIncludeCertsInChain = false;
success = cert.ExportToPfxFile("chilkat2.pfx","myPassword",bIncludeCertsInChain);
if (success != true) {
MessageBox.Show(cert.LastErrorText);
return;
}

MessageBox.Show("PFX created!");

Export All Certificates to .cer Files


Demonstrates how to export all certificates from a registry-based certificate store to .cer files where each
filename is the serial number.
Download Chilkat .NET for 2.0 / 3.5 Framework
Download Chilkat .NET for 64-bit 2.0 / 3.5 Framework (x64)
Download Chilkat .NET for 1.0 / 1.1 Framework
Chilkat.CreateCS ccs = new Chilkat.CreateCS();
ccs.ReadOnly = true;

// Open the current-user certificate store:


Chilkat.CertStore cs = null;
cs = ccs.OpenCurrentUserStore();

if (!(cs == null )) {

Chilkat.Cert cert = null;


int numCerts;
numCerts = cs.NumCertificates;
int i;
// Print the distinguished name of each certificate
for (i = 0; i <= numCerts - 1; i++) {
cert = cs.GetCertificate(i);

string filename;
filename = "certs/" + cert.SerialNumber + ".cer";

cert.ExportCertDerFile(filename);

}
else {
MessageBox.Show(ccs.LastErrorText);
}

List CSP Encryption Algorithms


Lists the encryption algorithms available for a CSP.
Download Chilkat .NET for 2.0 / 3.5 Framework
Download Chilkat .NET for 64-bit 2.0 / 3.5 Framework (x64)
Download Chilkat .NET for 1.0 / 1.1 Framework
Chilkat.Csp csp = new Chilkat.Csp();
csp.SetProviderMicrosoftRsaAes();

// Other commonly used CSPs can be selected with these


// methods:
// SetProviderMicrosoftBase
// SetProviderMicrosoftStrong
// SetProviderMicrosoftEnhanced()
// Otherwise the CSP can be selected by setting the ProviderName
// property to the exact name of the Cryptographic Service Provider.

int i;
int numEncryptAlgs;

numEncryptAlgs = csp.NumEncryptAlgorithms;
for (i = 0; i <= numEncryptAlgs - 1; i++) {
textBox1.Text += csp.GetEncryptionAlgorithm(i) + "\r\n";
}

// Sample output:
// RC2
// RC4
// DES
// 3DES TWO KEY
// 3DES
// AES 128
// AES 192
// AES 256

List CSP Hash Algorithms


Lists the hash algorithms available for a CSP.
Download Chilkat .NET for 2.0 / 3.5 Framework
Download Chilkat .NET for 64-bit 2.0 / 3.5 Framework (x64)
Download Chilkat .NET for 1.0 / 1.1 Framework
Chilkat.Csp csp = new Chilkat.Csp();
csp.SetProviderMicrosoftEnhanced();

// Other commonly used CSPs can be selected with these


// methods:
// SetProviderMicrosoftBase
// SetProviderMicrosoftStrong
// SetProviderMicrosoftEnhanced()
// Otherwise the CSP can be selected by setting the ProviderName
// property to the exact name of the Cryptographic Service Provider.

int i;
int numHashAlgs;

numHashAlgs = csp.NumHashAlgorithms;
for (i = 0; i <= numHashAlgs - 1; i++) {
textBox1.Text += csp.GetHashAlgorithm(i) + "\r\n";
}

// Sample output:
// SHA-1
// MD2
// MD4
// MD5
// SSL3 SHAMD5
// MAC
// HMAC

Auto-Install PFX within Windows Service


Demonstrates how to load a PFX from a Windows Service so that the private key is available for signing and
decrypting. The certificate is loaded into the Local Machine Certificate Store once. After that, it should always
be available.
Download Chilkat .NET for 2.0 / 3.5 Framework
Download Chilkat .NET for 64-bit 2.0 / 3.5 Framework (x64)
Download Chilkat .NET for 1.0 / 1.1 Framework
bool bNeedPfxImport;
bNeedPfxImport = true;

Chilkat.Cert cert = new Chilkat.Cert();


bool hasPrivKey;

// The LoadByCommonName method searches the registry-based


// Windows Current User Certificate Store and Local Machine Certificate
// Store for a certificate whose common name (CN) matches
// the argument:
bool success;
success = cert.LoadByCommonName("Chilkat Software, Inc.");
if (success == true) {
hasPrivKey = cert.HasPrivateKey();
if (hasPrivKey == true) {
// Certificate is available and has a private key that is accessible.
bNeedPfxImport = false;
}

// Do we need to load the PFX and import?


if (bNeedPfxImport == true) {

Chilkat.Pfx pfx = new Chilkat.Pfx();

bool bMachineKeyset;
bMachineKeyset = true;
bool bLocalMachineCertStore;
bLocalMachineCertStore = true;
bool bExportable;
bExportable = true;
bool bUseWarningDialog;
bUseWarningDialog = false;

success =
pfx.ImportPfxFile("c:/pfxFiles/myPfx.pfx","myPassword",bMachineKeyset,bLocalMachineCertStore,bExporta
ble,bUseWarningDialog);
if (success == false) {
// Failed to import the PFX.

}
else {

// The certificate(s) within the PFX have been installed.


// Now try loading again...
success = cert.LoadByCommonName("Chilkat Software, Inc.");
if (success == true) {

hasPrivKey = cert.HasPrivateKey();
// We should have access to the private key now...

# Code to List Certificates


Download Chilkat .NET for 2.0 / 3.5 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
How to list the digital certificates from the
Current User Certificate Store in the Windows Registry
This is a simple example demonstrating how to list the Current User certificates in C#.
// This C# example will list the certificates in the Current User
// Certificate Store in the Windows Registry
private void ListCerts_Click(object sender, System.EventArgs e)
{
// Create an object that will be used to create or
// open Chilkat.CertStore (certificate store) objects.
Chilkat.CreateCS ccs = new Chilkat.CreateCS();

// Open the current user certificate store.


Chilkat.CertStore certStore = ccs.OpenCurrentUserStore();

int i;
for (i = 0; i<certStore.NumCertificates-1; i++)
{
Chilkat.Cert cert = certStore.GetCertificate(i);
listBox1.Items.Add(cert.SubjectDN);
}

}
}
PKCS7 SignedData Detached Signature
How to create a PKCS7 detached signature. The resulting PKCS7 structure is encoded to a printable string
using hex or base64 encoding. The data being signed is not included in the PKCS#7 structure.
Download Chilkat .NET for 2.0 / 3.5 Framework
Download Chilkat .NET for 64-bit 2.0 / 3.5 Framework (x64)
Download Chilkat .NET for 1.0 / 1.1 Framework
Chilkat.Crypt2 crypt = new Chilkat.Crypt2();

// Any string argument automatically begins the 30-day trial.


bool success;
success = crypt.UnlockComponent("30-day trial");
if (success != true) {
MessageBox.Show("Crypt component unlock failed");
return;
}

Chilkat.Cert cert = new Chilkat.Cert();


success = cert.LoadByCommonName("Chilkat Software");
if (success != true) {
MessageBox.Show(cert.LastErrorText);
return;
}

// Make sure this certificate has a private key available:


bool bHasPrivateKey;
bHasPrivateKey = cert.HasPrivateKey();
if (bHasPrivateKey != true) {
MessageBox.Show("No private key available for signing.");
return;
}

// Tell the encryption component to use this cert.


crypt.SetSigningCert(cert);

string strData;
strData = "This is the data to be signed.";

// Indicate that the PKCS7 signature should be returned


// as a base64 encoded string:
crypt.EncodingMode = "base64";

// The EncodingMode may be set to other values such as


// "hex", "url", "quoted-printable", etc.

string strSignature;
strSignature = crypt.SignStringENC(strData);

textBox1.Text += strSignature + "\r\n";

// Now verify the signature against the original data.

// Tell the component what certificate to use for verification.


crypt.SetVerifyCert(cert);

success = crypt.VerifyStringENC(strData,strSignature);
if (success == true) {
MessageBox.Show("digital signature verified");
}
else {
MessageBox.Show("digital signature invalid");
}

// Try it with incorrect data:


success = crypt.VerifyStringENC("This is not the signed data",strSignature);
if (success == true) {
MessageBox.Show("digital signature verified");
}
else {
MessageBox.Show("digital signature invalid");
}
Simple Send Email
Download Chilkat .NET for 2.0 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
This is a very simple example showing how to send a basic email in C#.
// Create a mailman object for sending email.
Chilkat.MailMan mailman = new Chilkat.MailMan();

// Any string argument automatically begins the 30-day trial.


mailman.UnlockComponent("30-day trial");

// Set the SMTP server hostname.


mailman.SmtpHost = "smtp.earthlink.net";

// Create a simple email.


Chilkat.Email email = new Chilkat.Email();

email.Body = "This is the body";


email.Subject = "This is the subject";
email.AddTo("Chilkat Support","support@chilkatsoft.com");
email.From = "Jack Johnson <jj@chilkatsoft.com>";

// Send mail.
bool success;
success = mailman.SendEmail(email);
if (success)
{
MessageBox.Show("Sent mail!");
}
else
{
MessageBox.Show(mailman.LastErrorText);
}

Important: The download for this example does not contain the ChilkatDotNet.dll which
must be downloaded and installed separately at http://www.chilkatsoft.com/downloads.asp.
Once installed, add a reference to the DLL in the project by following the instructions at
http://www.example-code.com/vbdotnet/step2.asp
Simple Send HTML Email
Download Chilkat .NET for 2.0 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
This is a very simple example showing how to send a basic HTML email in C#.
// Create a mailman object for sending email.
Chilkat.MailMan mailman = new Chilkat.MailMan();

// Any string argument automatically begins the 30-day trial.


mailman.UnlockComponent("30-day trial");

// Set the SMTP server hostname.


mailman.SmtpHost = "smtp.earthlink.net";

// Create a simple HTML email.


Chilkat.Email email = new Chilkat.Email();
email.SetHtmlBody("<html><body><b><font color='red' size='+1'>This is red bold
text</font></b></html>");
email.Subject = "This is a simple HTML email";
email.AddTo("Chilkat Support","support@chilkatsoft.com");
email.From = "Jack Johnson <jj@chilkatsoft.com>";

// Send mail.
bool success;
success = mailman.SendEmail(email);
if (success)
{
MessageBox.Show("Sent HTML mail!");
}
else
{
MessageBox.Show(mailman.LastErrorText);
}

Important: The download for this example does not contain the ChilkatDotNet.dll which
must be downloaded and installed separately at http://www.chilkatsoft.com/downloads.asp.
Once installed, add a reference to the DLL in the project by following the instructions at
http://www.example-code.com/vbdotnet/step2.asp
ASP.NET: Display HTML Email
Filed under: HTML Email, asp.net — Tags: asp.net, display, HTML Email — admin @ 9:13 am
This post provides ASP.NET code (C#) to display an HTML email using the Chilkat .NET Email component. It
will provide a live example, as well as a download link to the sample code and data files.
This example is only concerned with displaying the HTML body of the email, including embedded images.
Displaying the text header fields (Subject, From, To, etc.) is trivial and not included in this example.
This example will load a Chilkat.Email object from a .eml file. It doesn’t matter how the Chilkat.Email object is
loaded — whether it’s from a POP3 or IMAP server, or from a file. Once it’s loaded, it may be displayed.
(Note: If you fetch headers-only from a POP3 or IMAP server, you will not have the full body so it cannot be
displayed. You must download the entire email before the body may be displayed.)
The sample .eml may be downloaded from this URL:
http://www.chilkatsoft.com/data/sampleHtmlWithAttach.eml
A live example is available at this URL:
http://www.chilkatsoft.com/displayEmail1.aspx
Click on the “Display Email” button to display the email.
The source code of the live example may be downloaded here:
http://www.chilkatsoft.com/data/AspNetDisplayEmail.zip
This contains two files: DisplayEmail1.aspx, DisplayEmail1.aspx.cs
How it Works
The Chilkat.Email object provides an AspUnpack2 method that unpacks the email’s embedded images (and
stylesheets) to temporary files on the web server. It modifies the HTML so that links are relative and point to
the temp files, and then returns the HTML in a byte array using the character encoding of the email. In this
example, our HTML page for displaying the email is utf-8 because we want to display email in any language.
Prior to calling AspUnpack2, the email.Charset property is set to “utf-8″ to convert the email to utf-8
(regardless of the original charset of the email). The HTML bytes returned from AspUnpack2 are converted to a
String, and this fills the InnerHTML of a “div”, which renders the HTML email.
DisplayEmail1.aspx Source Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DisplayEmail1.aspx.cs"
Inherits="DisplayEmail1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Display HTML Email</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Display Email"
Width="110px" /><br />
<br />
<asp:Label ID="LblStatus" runat="server" Text="Label" Width="128px"></asp:Label> </div>
</form>
<div style="border: 1px solid; padding=5px;" id="divDbg" runat="server">
Debug Log
</div>
<h2>The HTML body of the email:</h2>
<hr />
<div id="divEmail" runat="server">

</div>
<br />
</body>
</html>

DisplayEmail1.aspx.cs Source Code:


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

public partial class DisplayEmail1 : System.Web.UI.Page


{
private Chilkat.MailMan m_mailman = new Chilkat.MailMan();

protected void Page_Load(object sender, EventArgs e)


{
bool success = m_mailman.UnlockComponent("Anything for 30-day trial");
if (!success)
{
divDbg.InnerHtml = "Unlock Failed.";
LblStatus.Text = "Unlock Failed.";
}
else
{
divDbg.InnerHtml = "Unlock Successful.";
LblStatus.Text = "Unlock Successful.";
}

}
protected void Button1_Click(object sender, EventArgs e)
{
Chilkat.Email email = new Chilkat.Email();

// For demonstration purposes, load an email from a .eml file.


// This is an HTML email with embedded images.
bool success = email.LoadEml(Server.MapPath("data/sampleHtmlWithAttach.eml"));
if (!success)
{
divDbg.InnerHtml = email.LastErrorHtml;
LblStatus.Text = "EML Load Failed.";
return;
}

// Set a unique prefix so that all embedded images associated with


// this email begin with the same prefix. This makes it easier for your
// app to cleanup the files later...
string prefix = "abc_";
// This is the directory where embedded images will be placed:
string saveDir = Server.MapPath("data/emailHtmlFiles");
string relativeUrlPath = "data/emailHtmlFiles";
bool autoCleanFiles = true;

// Regardless of the charset of the email, make sure we get utf-8


// because our HTML page's charset is utf-8:
email.Charset = "utf-8";

// Get the utf-8 HTML:


byte[] htmlBytes = email.AspUnpack2(prefix, saveDir, relativeUrlPath, autoCleanFiles);
if (htmlBytes.Length == 0)
{
divDbg.InnerHtml = email.LastErrorHtml;
LblStatus.Text = “AspUnpack2 Failed.”;
return;
}

// Display the HTML email.


divEmail.InnerHtml = Encoding.UTF8.GetString(htmlBytes);
LblStatus.Text = “OK.”;
}
}
Send Multipart/Alternative Email
Download Chilkat .NET for 2.0 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
This example program shows how to send a multiplart/alternative email.
// Create a mailman object for sending email.
Chilkat.MailMan mailman = new Chilkat.MailMan();

// Any string argument automatically begins the 30-day trial.


mailman.UnlockComponent("30-day trial");

// Set the SMTP server host.


mailman.SmtpHost = "smtp.earthlink.net";

// Create a simple multipart/alternative email.


Chilkat.Email email = new Chilkat.Email();
email.Body = "This is the plain-text alternative";
email.AddHtmlAlternativeBody("<html><body><b><font color='red' size='+1'>This is the HTML
alternative body</font></b></html>");
email.Subject = "This is a simple multipart/alternative email";
email.AddTo("Chilkat Support","support@chilkatsoft.com");
email.From = "Buddahead <buddahead@chilkatsoft.com>";

// If you're curious, show the MIME text of the email to be sent..


MessageBox.Show(email.GetMime());

// Send email.
bool success;
success = mailman.SendEmail(email);
if (success)
{
MessageBox.Show("Sent HTML mail!");
}
else
{
MessageBox.Show(mailman.LastErrorText);
}

Important: The download for this example does not contain the ChilkatDotNet.dll which
must be downloaded and installed separately at http://www.chilkatsoft.com/downloads.asp.
Once installed, add a reference to the DLL in the project by following the instructions at
http://www.example-code.com/vbdotnet/step2.asp
Add File as Attachment to Email
Download Chilkat .NET for 2.0 / 3.5 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
This C# example program shows how to add a file attachment to an email and send it. To add multiple file
attachments, call AddFileAttachment once for each file.
bool success;

// Create a mailman object for sending email.


Chilkat.MailMan mailman = new Chilkat.MailMan();

// Any string argument automatically begins the 30-day trial.


mailman.UnlockComponent("30-day trial");

// Set the SMTP server host.


mailman.SmtpHost = "smtp.yourmailserver.com";

// Create a simple email with a file attachment.


Chilkat.Email email = new Chilkat.Email();

// This email will have both a plain-text body and an HTML body.
email.Body = "This is the plain-text alternative";
email.AddHtmlAlternativeBody("<html><body><b><font color='red' size='+1'>This is bold red
text.</font></b></html>");
email.Subject = "This email has a file attachment.";
email.AddTo("Chilkat Support","support@chilkatsoft.com");
email.From = "Hello World <hello@chilkatsoft.com>";

// Add a file attachment.


string contentType;
// Returns the content-type of the attachment (determined by the file extension)
// This return value is for informational purposes only.
contentType = email.AddFileAttachment("dude.gif");
if (contentType == null)
{
MessageBox.Show(email.LastErrorText);
return;
}

// If you're curious, show the MIME text of the email to be sent..


MessageBox.Show(email.GetMime());

// Send email.
success = mailman.SendEmail(email);
if (success)
{
MessageBox.Show("Sent mail with attachment!");
}
else
{
MessageBox.Show(mailman.LastErrorText);
}

Important: The download for this example does not contain the ChilkatDotNet.dll which
must be downloaded and installed separately at http://www.chilkatsoft.com/downloads.asp.
Once installed, add a reference to the DLL in the project by following the instructions at
http://www.example-code.com/vbdotnet/step2.asp
Multiple Email Attachments
Download Chilkat .NET for 2.0 / 3.5 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
Demonstrates how to add several files as attachments to an email.
bool success;

// Create a mailman object for sending email.


Chilkat.MailMan mailman = new Chilkat.MailMan();

// Any string argument automatically begins the 30-day trial.


mailman.UnlockComponent("30-day trial");

// Set the SMTP server host.


mailman.SmtpHost = "smtp.earthlink.net";

// Create a simple email with several file attachments.


Chilkat.Email email = new Chilkat.Email();

// This email will have both a plain-text body and an HTML body.
email.Body = "This is the plain-text alternative";
email.AddHtmlAlternativeBody("<html><body><b><font color='red' size='+1'>This is bold red
text.</font></b></html>");
email.Subject = "This email has a file attachment.";
email.AddTo("Chilkat Support","support@chilkatsoft.com");
email.From = "Hello World <hello@chilkatsoft.com>";

// Add a file attachment.


string contentType;
// Returns the content-type of the attachment (determined by the file extension)
// This return value is for informational purposes only.
contentType = email.AddFileAttachment("dude.gif");
if (contentType == null)
{
MessageBox.Show(email.LastErrorText);
return;
}

// Add another file attachment.


contentType = email.AddFileAttachment("dude2.gif");
if (contentType == null)
{
MessageBox.Show(email.LastErrorText);
return;
}

// Send email.
success = mailman.SendEmail(email);
if (success)
{
MessageBox.Show("Sent mail with attachments!");
}
else
{
MessageBox.Show(mailman.LastErrorText);
}

Important: The download for this example does not contain the ChilkatDotNet.dll which
must be downloaded and installed separately at http://www.chilkatsoft.com/downloads.asp.
Once installed, add a reference to the DLL in the project by following the instructions at
http://www.example-code.com/vbdotnet/step2.asp
Zip Email Attachments before Sending
Download Chilkat .NET for 2.0 / 3.5 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
C# code demonstrating how to add file attachments and then Zip them so that a single Zip file attachment is sent
with the email. This only requires Chilkat Mail, and not Chilkat Zip.
bool success;

// Create a mailman object for sending email.


Chilkat.MailMan mailman = new Chilkat.MailMan();

// Any string argument automatically begins the 30-day trial.


mailman.UnlockComponent("30-day trial");

// Set the SMTP server host.


mailman.SmtpHost = "smtp.earthlink.net";

// Create a simple email with a Zip file attachment.


Chilkat.Email email = new Chilkat.Email();

// This email will have both a plain-text body and an HTML body.
email.Body = "This is the plain-text alternative";
email.AddHtmlAlternativeBody("<html><body><b><font color='red' size='+1'>This is bold red
text.</font></b></html>");
email.Subject = "This email has a file attachment.";
email.AddTo("Chilkat Support","support@chilkatsoft.com");
email.From = "Hello World <hello@chilkatsoft.com>";

// Add a file attachment.


string contentType;
// Returns the content-type of the attachment (determined by the file extension)
// This return value is for informational purposes only.
contentType = email.AddFileAttachment("dude.gif");
if (contentType == null)
{
MessageBox.Show(email.LastErrorText);
return;
}

// Add another file attachment.


contentType = email.AddFileAttachment("dude2.gif");
if (contentType == null)
{
MessageBox.Show(email.LastErrorText);
return;
}

// Replace the attachments with a single Zip archive that contains the files already attached.
email.ZipAttachments("dudes.zip");

// Send email, the recipient will receive an email with a single attachment (dudes.zip)
// that contains 2 file: dude.gif and dude2.gif.
success = mailman.SendEmail(email);
if (success)
{
MessageBox.Show("Sent mail with Zip attachment!");
}
else
{
MessageBox.Show(mailman.LastErrorText);
}

Important: The download for this example does not contain the ChilkatDotNet.dll which
must be downloaded and installed separately at http://www.chilkatsoft.com/downloads.asp.
Once installed, add a reference to the DLL in the project by following the instructions at
http://www.example-code.com/vbdotnet/step2.asp
Send High-Priority Email
Download Chilkat .NET for 2.0 / 3.5 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
C# source code showing how to send a high-priority mail.
bool success;

// Create a mailman object for sending email.


Chilkat.MailMan mailman = new Chilkat.MailMan();

// Any string argument automatically begins the 30-day trial.


mailman.UnlockComponent("30-day trial");

// Set the SMTP server.


mailman.SmtpHost = "smtp.earthlink.net";

// Create a high-priority email.


Chilkat.Email email = new Chilkat.Email();

// Set the basic email stuff: body, subject, "from", "to"


email.Body = "This is the email body";
email.Subject = "This is the email subject";
email.AddTo("Chilkat Support","support@chilkatsoft.com");
email.From = "Programmer <programmer@chilkatsoft.com>";

//You can add the X-Priority header field and give it the value string "1".
//For example: email.AddHeaderField "X-Priority","1" This is the most common way of
// setting the priority of an email. "3" is normal, and "5" is the lowest.
// "2" and "4" are in-betweens, and frankly I've never seen anything
// but "1" or "3" used. Microsoft Outlook adds these header fields when
// setting a message to High priority:

// X-Priority: 1 (Highest)
// X-MSMail-Priority: High
// Importance: High

// This field alone is enough to make the email high-priority.


email.AddHeaderField("X-Priority","1");

success = mailman.SendEmail(email);
if (success)
{
MessageBox.Show("Sent high-priority email!");
}
else
{
MessageBox.Show(mailman.LastErrorText);
}

Important: The download for this example does not contain the ChilkatDotNet.dll which
must be downloaded and installed separately at http://www.chilkatsoft.com/downloads.asp.
Once installed, add a reference to the DLL in the project by following the instructions at
http://www.example-code.com/vbdotnet/step2.asp
Add CC Recipients to an Email
Download Chilkat .NET for 2.0 / 3.5 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
C# source code showing how to add multiple CC recipients to an email.
bool success = false;

// Create a mailman object for sending email.


Chilkat.MailMan mailman = new Chilkat.MailMan();

// Any string argument automatically begins the 30-day trial.


mailman.UnlockComponent("30-day trial");

// Set the SMTP server.


mailman.SmtpHost = "smtp.earthlink.net";

// Create an email with multiple CC recipients.


Chilkat.Email email = new Chilkat.Email();

// Set the basic email stuff: body, subject, "from", "to"


email.Body = "This is the email body";
email.Subject = "This is the email subject";
email.AddTo("Chilkat Support","support@chilkatsoft.com");
email.From = "Programmer <programmer@chilkatsoft.com>";

// To add multiple CC recipients, you can call AddCC multiple times


// and/or call AddMultipleCC with a comma-separated list of email addresses.
// Either method can be called any number of times. Chilkat automatically
// removes duplicates.
email.AddCC("","sales@chilkatsoft.com");
email.AddCC("Chilkat HR","hr@chilkatsof.com");
email.AddMultipleCC("Jack Frost <jfrost@chilkatsoft.com>, matt@chilkatsoft.com, Bob
<bob@chilkatsoft.com>");

// If you are curious, look at the full MIME text of the email...
MessageBox.Show(email.GetMime());

success = mailman.SendEmail(email);
if (success)
{
MessageBox.Show("Sent CC mail!");
}
else
{
MessageBox.Show(mailman.LastErrorText);
}

Important: The download for this example does not contain the ChilkatDotNet.dll which
must be downloaded and installed separately at http://www.chilkatsoft.com/downloads.asp.
Once installed, add a reference to the DLL in the project by following the instructions at
http://www.example-code.com/vbdotnet/step2.asp
Send BCC Email
Download Chilkat .NET for 2.0 / 3.5 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
C# sample program showing how to send email to multiple BCC recipients.
bool success = false;

// Create a mailman object for sending email.


Chilkat.MailMan mailman = new Chilkat.MailMan();

// Any string argument automatically begins the 30-day trial.


mailman.UnlockComponent("30-day trial");

// Set the SMTP server.


mailman.SmtpHost = "smtp.earthlink.net";

// Create an email with multiple BCC recipients.


Chilkat.Email email = new Chilkat.Email();

// Set the basic email stuff: body, subject, "from", "to"


email.Body = "This is the email body";
email.Subject = "This is the email subject";
email.AddTo("Chilkat Support","support@chilkatsoft.com");
email.From = "Programmer <programmer@chilkatsoft.com>";

// To add multiple BCC recipients, you can call AddBcc multiple times
// and/or call AddMultipleBcc with a comma-separated list of email addresses.
// Either method can be called any number of times. Chilkat automatically
// removes duplicates.
email.AddBcc("","sales@chilkatsoft.com");
email.AddBcc("Chilkat HR","hr@chilkatsof.com");
email.AddMultipleBcc("Jack Frost <jfrost@chilkatsoft.com>, matt@chilkatsoft.com, Bob
<bob@chilkatsoft.com>");

success = mailman.SendEmail(email);
if (success)
{
MessageBox.Show("Sent BCC email!");
}
else
{
MessageBox.Show(mailman.LastErrorText);
}
Set a Bounce Address when Sending Email
Download Chilkat .NET for 2.0 / 3.5 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
C# sample program showing how to set a bounce address when sending an email. Non-delivery messages will
be sent to the bounce address.
bool success = false;

// Create a mailman object for sending email.


Chilkat.MailMan mailman = new Chilkat.MailMan();

// Any string argument automatically begins the 30-day trial.


mailman.UnlockComponent("30-day trial");

// Set the SMTP server.


mailman.SmtpHost = "smtp.earthlink.net";

// Create an email with with a bounce address that is different from the "From" address.
Chilkat.Email email = new Chilkat.Email();

// Set the basic email stuff: body, subject, "from", "to"


email.Body = "This is the email body";
email.Subject = "This is the email subject";
email.AddTo("Chilkat Support","support@chilkatsoft.com");
email.From = "Programmer <programmer@chilkatsoft.com>";

// Set the bounce address. If the email bounces, the MDN will be delivered to the bounce address.
email.BounceAddress = "bounce@chilkatsoft.com";

success = mailman.SendEmail(email);
if (success)
{
MessageBox.Show("Sent email!");
}
else
{
MessageBox.Show(mailman.LastErrorText);
}
Set Reply-To Address Different than "From" Address
Download Chilkat .NET for 2.0 / 3.5 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
C# code showing how to specify a "reply-to" address that is different than the "From" address when sending
email.
bool success = false;

// Create a mailman object for sending email.


Chilkat.MailMan mailman = new Chilkat.MailMan();

// Any string argument automatically begins the 30-day trial.


mailman.UnlockComponent("30-day trial");

// Set the SMTP server.


mailman.SmtpHost = "smtp.earthlink.net";

// Create an email with a reply-to address that is different from the "From" address.
Chilkat.Email email = new Chilkat.Email();

// Set the basic email stuff: body, subject, "from", "to"


email.Body = "This is the email body";
email.Subject = "This is the email subject";
email.AddTo("Chilkat Support","support@chilkatsoft.com");
email.From = "Programmer <programmer@chilkatsoft.com>";

// Set the reply-to address.


email.ReplyTo = "reply@chilkatsoft.com";

success = mailman.SendEmail(email);
if (success)
{
MessageBox.Show("Sent email!");
}
else
{
MessageBox.Show(mailman.LastErrorText);
}
Send iso-8859-1 Email with European Accented Characters
C# source code example to send an email using iso-8859-1 characters.
bool success = false;

// Create a mailman object for sending email.


Chilkat.MailMan mailman = new Chilkat.MailMan();

// Any string argument automatically begins the 30-day trial.


mailman.UnlockComponent("30-day trial");

// Set the SMTP server.


mailman.SmtpHost = "smtp.earthlink.net";

// Create an email that uses characters with diacritics (accented characters)


Chilkat.Email email = new Chilkat.Email();

// Set the basic email stuff: body, subject, "from", "to"


email.Body = "Þ ß à á This is the email body";
email.Subject = "Þ ß à á This is the email subject";
email.AddTo("Þ ß à á","support@chilkatsoft.com");
email.From = "Þ ß à á <programmer@chilkatsoft.com>";
// Chilkat should automatically recognize this as having characters with diacritics,
// and will by default encode the email as iso-8859-1
// It is possible to verify this by examining the full MIME text of the email:
MessageBox.Show(email.GetMime());

// The MIME that Chilkat generates for this email looks like this:
/*
*
MIME-Version: 1.0
Date: Thu, 02 Sep 2004 15:18:45 -0500
Message-ID: <CHILKAT-MID-d8e999ca-2691-48ef-9e10-abedbbaad1c1@DotNetDev>
X-Mailer: Chilkat Software Inc (http://www.chilkatsoft.com)
X-Priority: 3 (Normal)
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
subject: =?iso-8859-1?Q?=DE_=DF_=E0_=E1_This_is_the_email_subject?=
To: =?iso-8859-1?Q?=DE_=DF_=E0_=E1?= <support@chilkatsoft.com>
From: =?iso-8859-1?Q?=DE_=DF_=E0_=E1?= <programmer@chilkatsoft.com>
return-path: programmer@chilkatsoft.com

=DE =DF =E0 =E1 This is the email body


*/

// To be absolutely sure the email is encoded as iso-8859-1, set the Charset property:
email.Charset = "iso-8859-1";
// One point to remember: Chilkat does not "Q" encode header fields that do not need encoding.
// (i.e. fields that are 7-bit us-ascii already and have no accented (8-bit) characters)

success = mailman.SendEmail(email);
if (success)
{
MessageBox.Show("Sent email!");
}
else
{
MessageBox.Show(mailman.LastErrorText);
}
Send Hindi Email
C# source code showing how to send an email with Hindi characters.
bool success = false;

// Create a mailman object for sending email.


Chilkat.MailMan mailman = new Chilkat.MailMan();

// Any string argument automatically begins the 30-day trial.


mailman.UnlockComponent("30-day trial");

// Set the SMTP server.


mailman.SmtpHost = "smtp.earthlink.net";

// Create an email object


Chilkat.Email email = new Chilkat.Email();

// Set the basic email stuff: body, subject, "from", "to"


// (This source code file was saved as Unicode (code page 1200).)
email.Body = "मैं काँच खा सकता हूँ, मुझे उस से कोई पीडा नहीं होती.";
email.Subject = "मैं काँच खा सकता हूँ, मुझे उस से कोई पीडा नहीं होती.";
email.AddTo("मैं काँच","support@chilkatsoft.com");
email.From = "मैं काँच <programmer@chilkatsoft.com>";

// Chilkat will send Hindi email encoded as utf-8.

// It is possible to verify this by examining the full MIME text of the email:
MessageBox.Show(email.GetMime());

// Send the Hindi email...


success = mailman.SendEmail(email);
if (success)
{
MessageBox.Show("Sent email!");
}
else
{
MessageBox.Show(mailman.LastErrorText);
}

Send HTML Email with Embedded Image


C# source code sample showing how to send an HTML email with images embedded within the HTML.
bool success = false;

// Create a mailman object for sending email.


Chilkat.MailMan mailman = new Chilkat.MailMan();

// Any string argument automatically begins the 30-day trial.


mailman.UnlockComponent("30-day trial");

// Set the SMTP server.


mailman.SmtpHost = "smtp.earthlink.net";

// Create an email object


Chilkat.Email email = new Chilkat.Email();

// Add an embedded image to the HTML email.


string cid = email.AddRelatedFile("dude.gif");
if (cid == null)
{
MessageBox.Show(email.LastErrorText);
return;
}

// Update the HTML to reference the image using the CID


string htmlBody = "<html><body>Embedded Image:<br><img src=\"cid:IMAGE_CID\"></body></html>";
htmlBody = htmlBody.Replace("IMAGE_CID",cid);

// Set the basic email stuff: HTML body, subject, "from", "to"
email.SetHtmlBody(htmlBody);
email.Subject = "This is an HTML email with an embedded image.";
email.AddTo("Chilkat Support","support@chilkatsoft.com");
email.From = "Programmer <programmer@chilkatsoft.com>";
success = mailman.SendEmail(email);
if (!success)
{
MessageBox.Show(mailman.LastErrorText);
return;
}
Email Distribution List with Mail Merge
Download Chilkat .NET for 2.0 / 3.5 Framework
Download Chilkat .NET for 1.0 / 1.1 Framework
C# source code example showing how to send email using a distribution list with mail-merge.
bool success = false;

// Create a mailman object for sending email.


Chilkat.MailMan mailman = new Chilkat.MailMan();

// Any string argument automatically begins the 30-day trial.


mailman.UnlockComponent("30-day trial");

// Set the SMTP server.


mailman.SmtpHost = "smtp.earthlink.net";

// Create an array of email addresses.


// This is where you might load email addresses from a file,
// or load email addresses from a database such as Access, SQL Server, Oracle, MySQL, etc.
Chilkat.StringArray array = new Chilkat.StringArray();
array.Unique = true; // Do not allow duplicates in the array.

// Chilkat will be able to parse the full email addresses...


array.Append("Chilkat Support <support@chilkatsoft.com>");
array.Append("\"Chilkat Sales\" <sales@chilkatsoft.com>");
array.Append("<matt@chilkatsoft.com>");
array.Append("joe@chilkatsoft.com");

Chilkat.Email email = new Chilkat.Email();

// Make this email have both HTML and plain-text alternatives.


// Be sure to use CRLF line endings in plain-text email.
email.AddPlainTextAlternativeBody("Hello CUSTOMER_NAME\r\nThis is a test");
email.AddHtmlAlternativeBody("<html><body>Hello CUSTOMER_NAME<br>This is a
test</body></html>");

email.Subject = "CUSTOMER_NAME: This is a test.";

email.FromName = "Bob";
email.FromAddress = "bob@chilkatsoft.com";

int i;
int numEmails = array.Count;

string friendlyName;
for (i=0; i<numEmails; i++)
{
email.ClearTo();

// We call AddMultipleTo even though we are only adding a single


// email address. AddMultipleTo parses a comma separated list of
// email addresses, each of which may or may not include the
// friendly name.
email.AddMultipleTo(array.GetString(i));

// Get the friendly name that was in the email address.


friendlyName = email.GetToName(0);
if (friendlyName.Length == 0)
{
friendlyName = friendlyName + "Customer";
}
// Set the replacement pattern. When the email is sent, all occurances of
// CUSTOMER_NAME are replaced with the replacement string.
email.SetReplacePattern("CUSTOMER_NAME",friendlyName);

// The email can have any number of replacement patterns. Simply


// set a replace pattern for each.
// email.SetReplacePattern("PATTERN2","replacement2");
// email.SetReplacePattern("PATTERN3","replacement3");

bool sendQueued = true;

// One option is to send the email in the background using the SMTPQ service:
if (sendQueued)
{
// Sending the email using SMTPQ allows for emails to be sent by multiple
// threads simultaneously by the SMTPQ process. The email sending will
// also survive system reboots / crashes because it will resume when the
// service restarts on system startup.
if (!mailman.SendQ(email))
{
// We could send the email in-process:
MessageBox.Show(mailman.LastErrorText);
break;
}
}
else
{
// Or... the mail can be sent in-process.
if (!mailman.SendEmail(email))
{
// We could send the email in-process:
MessageBox.Show(mailman.LastErrorText);
break;
}
}
}
http://www.example-code.com/csharp/email.asp

Вам также может понравиться