Posts Tagged ‘SMTP’

Send vCard business card

Saturday, March 10th, 2012

Mail.dll .NET email component makes sending vCard business cards easy.

MailBuilder class contains AddVCard method, that can be used to add vCard business card as a attachment to your email.
You can use VCard class to create VCARD business card. It provides easy to use API to add phone, email and address information.

Here’s the simple sample showing how to send email with VCard business card:

// C#

// Create VCard business card

VCard vCard = new VCard();

vCard.FullName = "John Doe";
vCard.Name = new VCardName("John", "Doe");
vCard.Organization = new VCardOrganization("Example");
vCard.Title = "CEO";
vCard.Url = "http://www.example.com";

VCardEmail workEmail = new VCardEmail("john.doe@example.com");
workEmail.MarkWork();
workEmail.MarkPreferred();
vCard.Emails.Add(workEmail);

VCardEmail homeEmail = new VCardEmail("john.doe@gmail.com");
homeEmail.MarkHome();
vCard.Emails.Add(homeEmail);

VCardAddress workAddress = new VCardAddress("", "", "501 E. Middlefield Rd.", "Mountain View", "CA", "94043", "U.S.A.");
workAddress.MarkWork();
vCard.Addresses.Add(workAddress);

VCardAddress homeAddress = new VCardAddress("", "", "6544 Battleford Drive", "Raleigh", "NC", "27613-3502", "U.S.A.");
homeAddress.MarkHome();
vCard.Addresses.Add(homeAddress);

VCardPhone homePhone = new VCardPhone("+1-919-676-9515");
homePhone.MarkHome();
vCard.Phones.Add(homePhone);

VCardPhone workPhone = new VCardPhone();
workPhone.AsUri("tel:+1-919-676-9564");
workPhone.MarkWork();
workPhone.MarkFax();
workPhone.MarkVoice();
vCard.Phones.Add(workPhone);

// Create email message

MailBuilder builder = new MailBuilder();
builder.From.Add(new MailBox("john.doe@example.com"));
builder.To.Add(new MailBox("bob@example.com"));
builder.Text = "Business card";
builder.Text = "Here's my business card.";
builder.AddVCard(vCard);
IMail email = builder.Create();

// Send email message using SMTP protocol

using(Smtp smtp  = new Smtp())
{
    smtp.ConnectSSL("imap.example.com");
    smtp.UseBestLogin("user", "password");
    smtp.SendMessage(email);
    smtp.Close();
}
' VB.NET

' Create VCard business card

Dim vCard As New VCard()

vCard.FullName = "John Doe"
vCard.Name = New VCardName("John", "Doe")
vCard.Organization = New VCardOrganization("Example")
vCard.Title = "CEO"
vCard.Url = "http://www.example.com"

Dim workEmail As New VCardEmail("john.doe@example.com")
workEmail.MarkWork()
workEmail.MarkPreferred()
vCard.Emails.Add(workEmail)

Dim homeEmail As New VCardEmail("john.doe@gmail.com")
homeEmail.MarkHome()
vCard.Emails.Add(homeEmail)

Dim workAddress As New VCardAddress("", "", "501 E. Middlefield Rd.", "Mountain View", "CA", "94043", _
	"U.S.A.")
workAddress.MarkWork()
vCard.Addresses.Add(workAddress)

Dim homeAddress As New VCardAddress("", "", "6544 Battleford Drive", "Raleigh", "NC", "27613-3502", _
	"U.S.A.")
homeAddress.MarkHome()
vCard.Addresses.Add(homeAddress)

Dim homePhone As New VCardPhone("+1-919-676-9515")
homePhone.MarkHome()
vCard.Phones.Add(homePhone)

Dim workPhone As New VCardPhone()
workPhone.AsUri("tel:+1-919-676-9564")
workPhone.MarkWork()
workPhone.MarkFax()
workPhone.MarkVoice()
vCard.Phones.Add(workPhone)

' Create email message

Dim builder As New MailBuilder()
builder.From.Add(New MailBox("john.doe@example.com"))
builder.[To].Add(New MailBox("bob@example.com"))
builder.Text = "Business card"
builder.Text = "Here's my business card."
builder.AddVCard(vCard)
Dim email As IMail = builder.Create()

' Send email message using SMTP protocol

Using smtp As New Smtp()
	smtp.ConnectSSL("imap.example.com")
	smtp.UseBestLogin("user", "password")
	smtp.SendMessage(email)
	smtp.Close()
End Using

Such email can be parsed and VCard extracted.

Send iCalendar meeting requests for different timezone

Sunday, January 1st, 2012

Usually you define time of an event in relation to UTC time zone.

If you need to define event on 9:00 o’clock in Alaska you simply need to subtract 9 hours from event time to get the event time in UTC
(18:00:00). 18 – 9 = 9.

It all works great in December (Alaska is UTC-9), but in May, daylight saving time is in effect in Alaska (Alaska is UTC-8 then).

If the event is recurring, in May, event is going to be held on 10:00 Alaska time (18 – 8 = 10). Which is most likely not what you want.

As the time zones in different parts of world change way to often to reflect these changes in Mail.dll, you’ll need to specify the time zone when creating new event (including the daylight savings time).

Here’s the sample:

// C#
using Fluent = Limilabs.Mail.Fluent;
using Limilabs.Client.SMTP;
using Limilabs.Mail;
using Limilabs.Mail.Appointments;

Appointment appointment = new Appointment();

// Create time zone
VTimeZone alaska = appointment.AddTimeZone();
alaska.TimeZoneId = "America/Anchorage";

// Define standard time offset
var standardRecurring = new RecurringRule();
standardRecurring.Frequency = Frequency.Yearly;
standardRecurring.ByDay.Add(Weekday.Sunday);
standardRecurring.ByMonths.Add(11);

var standard = new StandardOffset
{
    Name = "AKST",
    Start = new DateTime(1970, 11, 01, 02, 00, 00),
    OffsetFrom = TimeSpan.FromHours(-8),
    OffsetTo = TimeSpan.FromHours(-9),
    RecurringRule = standardRecurring
};

// Define daylight time offset
var daylightRecurring = new RecurringRule();
daylightRecurring.Frequency = Frequency.Yearly;
daylightRecurring.ByDay.Add(new Weekday(2, Weekday.Sunday));
daylightRecurring.ByMonths.Add(3);

var daylight = new DaylightOffset
{
    Name = "AKDT",
    Start = new DateTime(1970, 03, 08, 02, 00, 00),
    OffsetFrom = TimeSpan.FromHours(-9),
    OffsetTo = TimeSpan.FromHours(-8),
    RecurringRule = daylightRecurring
};

alaska.Standard.Add(standard);
alaska.Daylight.Add(daylight);

// Define event
Event e = appointment.AddEvent();
e.Start = new DateTime(2007, 08, 17, 12, 00, 00);
e.End = new DateTime(2007, 08, 17, 12, 30, 00);
e.Summary = "At noon in Alaska";
e.InTimeZone(alaska);

e.SetOrganizer(new Person("Alice", "alice@example.org"));

e.AddParticipant(new Participant(
    "Bob", "bob@example.org", ParticipationRole.Required, true));
e.AddParticipant(new Participant(
    "Tom", "tom@example.org", ParticipationRole.Optional, true));
e.AddParticipant(new Participant(
    "Alice", "alice@example.org", ParticipationRole.Required, true));

Alarm alarm = e.AddAlarm();
alarm.BeforeStart(TimeSpan.FromMinutes(15));

IMail email = Fluent.Mail
    .Text("Status meeting at noon in Alaska.")
    .Subject("Status meeting")
    .From("alice@example.org")
    .To("bob@example.org")
    .To("tom@example.org")
    .AddAppointment(appointment)
    .Create();

using (Smtp smtp = new Smtp())
{
    smtp.Connect("smtp.example.org"); // or ConnectSSL
    smtp.UseBestLogin("user", "password");
    smtp.SendMessage(email);
    smtp.Close();
}
' VB.NET
Imports Fluent = Limilabs.Mail.Fluent
Imports Limilabs.Client.SMTP
Imports Limilabs.Mail
Imports Limilabs.Mail.Appointments

Dim appointment As New Appointment()

' Create time zone
Dim alaska As VTimeZone = appointment.AddTimeZone()
alaska.TimeZoneId = "America/Anchorage"

' Define standard time offset
Dim standardRecurring = New RecurringRule()
standardRecurring.Frequency = Frequency.Yearly
standardRecurring.ByDay.Add(Weekday.Sunday)
standardRecurring.ByMonths.Add(11)

Dim standard = New StandardOffset() With { _
	.Name = "AKST", _
	.Start = New DateTime(1970, 11, 1, 2, 0, 0), _
	.OffsetFrom = TimeSpan.FromHours(-8), _
	.OffsetTo = TimeSpan.FromHours(-9), _
	.RecurringRule = standardRecurring _
}

' Define daylight time offset
Dim daylightRecurring = New RecurringRule()
daylightRecurring.Frequency = Frequency.Yearly
daylightRecurring.ByDay.Add(New Weekday(2, Weekday.Sunday))
daylightRecurring.ByMonths.Add(3)

Dim daylight = New DaylightOffset() With { _
	.Name = "AKDT", _
	.Start = New DateTime(1970, 3, 8, 2, 0, 0), _
	.OffsetFrom = TimeSpan.FromHours(-9), _
	.OffsetTo = TimeSpan.FromHours(-8), _
	.RecurringRule = daylightRecurring _
}

alaska.Standard.Add(standard)
alaska.Daylight.Add(daylight)

' Define event
Dim e As [Event] = appointment.AddEvent()
e.Start = New DateTime(2007, 8, 17, 12, 0, 0)
e.[End] = New DateTime(2007, 8, 17, 12, 30, 0)
e.Summary = "At noon in Alaska"
e.InTimeZone(alaska)

e.SetOrganizer(New Person("Alice", "alice@example.org"))

e.AddParticipant(New Participant( _
	"Bob", "bob@example.org", ParticipationRole.Required, True))
e.AddParticipant(New Participant( _
	"Tom", "tom@example.org", ParticipationRole.[Optional], True))
e.AddParticipant(New Participant( _
	"Alice", "alice@example.org", ParticipationRole.Required, True))

Dim alarm As Alarm = e.AddAlarm()
alarm.BeforeStart(TimeSpan.FromMinutes(15))

Dim email As IMail = Fluent.Mail _
	.Text("Status meeting at noon in Alaska.") _
	.Subject("Status meeting") _
	.From("alice@example.org") _
	.[To]("bob@example.org") _
	.[To]("tom@example.org") _
	.AddAppointment(appointment) _
	.Create()

Using smtp As New Smtp()
	smtp.Connect("smtp.example.org") 	' or ConnectSSL
	smtp.UseBestLogin("user", "password")
	smtp.SendMessage(email)
	smtp.Close()
End Using

Reply to an email

Wednesday, December 28th, 2011

You can use Mail.dll to easy reply to an HTML and plain-text emails.

ReplyBuilder class allows you to specify custom HTML and plain-text reply templates. Mail.dll will parse HTML, extract body part, and build-in template engine will do the rest to create nicely formatted reply with all attachments, To and Cc fields set.

The next great thing is that plain-text version of the email is generated automatically.

You can also take advantage of ReplyAll method that makes it easy to reply to all: senders of the message and all To and Cc recipients

In our example we’ll use Mail.dll IMAP client to download first message from an IMAP server. Then we’ll use ReplyBuilder to create a reply email message. Finally we’ll use Mail.dll SMTP client to send this message.

// C#

IMail original = GetFirstMessage();

ReplyBuilder replyBuilder = original.Reply();
// You can specify your own custom template:
replyBuilder.HtmlReplyTemplate =
    "[Html]" +
    "<br /><br />" +
    "On [Original.Date] [Original.Sender.Name] wrote:" +
    "<blockquote " +
        "style='margin-left: 1em; " +
        "padding-left: 1em; " +
        "border-left: 1px #ccc solid;'>" +
    "[QuoteHtml]" +
    "</blockquote>";

replyBuilder.Html =
    "Alice, <br/><br/>thanks for your email.";

MailBuilder builder = replyBuilder.ReplyToAll(
    new MailBox("bob@example.org", "Bob"));

// You can add attachments to your reply
//builder.AddAttachment("report.csv");

IMail reply = builder.Create();

using (Smtp smtp = new Smtp())
{
    smtp.Connect("smtp.example.com"); // or ConnectSSL
    smtp.UseBestLogin("user", "password");
    smtp.SendMessage(reply);
    smtp.Close();
}

static IMail GetFirstMessage()
{
    IMail email;
    using (Imap imap = new Imap())
    {
        imap.Connect("imap.example.com"); // or ConnectSSL if you want to use SSL
        imap.UseBestLogin("user", "password");
        List<long> uids = imap.GetAll();
        if (uids.Count == 0)
            throw new Exception("There are no messages");
        string eml = imap.GetMessageByUID(uids[0]);
        email = new MailBuilder().CreateFromEml(eml);
        imap.Close();
    }
    return email;
}
' VB.NET

Dim original As IMail = GetFirstMessage()

Dim replyBuilder As ReplyBuilder = original.Reply()

' You can specify your own custom template:
replyBuilder.HtmlReplyTemplate = _
    "[Html]" + _
    "<br /><br />" + _
    "On [Original.Date] [Original.Sender.Name] wrote:" + _
    "<blockquote " + _
        "style='margin-left: 1em; " + _
        "padding-left: 1em; " + _
        "border-left: 1px #ccc solid;'>" + _
    "[QuoteHtml]" + _
    "</blockquote>"

replyBuilder.Html = _
    "Alice, <br/><br/>thanks for your email."

Dim builder As MailBuilder = replyBuilder.ReplyToAll( _
    New MailBox("bob@example.org", "Bob"))

' You can add attachments to your reply
'builder.AddAttachment("report.csv")

Dim reply As IMail = builder.Create()

Using smtp As New Smtp()
	smtp.Connect("smtp.example.com") ' or ConnectSSL
	smtp.UseBestLogin("user", "password")
	smtp.SendMessage(reply)
	smtp.Close()
End Using

Private Shared Function GetFirstMessage() As IMail
	Dim email As IMail
	Using imap As New Imap()
		imap.Connect("imap.example.com")
		' or ConnectSSL if you want to use SSL
		imap.UseBestLogin("user", "password")
		Dim uids As List(Of Long) = imap.GetAll()
		If uids.Count = 0 Then
			Throw New Exception("There are no messages")
		End If
		Dim eml As String = imap.GetMessageByUID(uids(0))
		email = New MailBuilder().CreateFromEml(eml)
		imap.Close()
	End Using
	Return email
End Function

Get supported authentication methods (IMAP, POP3, SMTP)

Thursday, October 6th, 2011

You can use SupportedAuthenticationMethods to retrieve all authentication methods supported by the server:

// C#

using (Imap client = new Imap())
{
    client.ConnectSSL("imap.example.org");
    client.UseBestLogin("user", "password");

    Console.WriteLine("Supported methods:");

    foreach (var method in client.SupportedAuthenticationMethods())
    {
        Console.WriteLine(method.Name);
    }

    Console.WriteLine("Supports CramMD5:");

    bool supportsCramMD5 = client.SupportedAuthenticationMethods()
        .Contains(ImapAuthenticationMethod.CramMD5);

    Console.WriteLine(supportsCramMD5);

    client.Close();
}
' VB.NET

Using client As New Imap()
    client.ConnectSSL("imap.example.org")
    client.UseBestLogin("user", "password")

    Console.WriteLine("Supported methods:")

    For Each method As ImapAuthenticationMethod In client.SupportedAuthenticationMethods()
	    Console.WriteLine(method.Name)
    Next

    Console.WriteLine("Supports CramMD5:")

    Dim supportsCramMD5 As Boolean = client.SupportedAuthenticationMethods() _
        .Contains(ImapAuthenticationMethod.CramMD5)

    Console.WriteLine(supportsCramMD5)

    client.Close()
End Using

For example Gmail produces following output:

Supported method s:
IMAP4rev1
UNSELECT
IDLE
NAMESPACE
QUOTA
ID
XLIST
CHILDREN
X-GM-EXT-1
UIDPLUS
COMPRESS

Supports CramMD5:
False

We take great care for the API to look similar for all protocols (IMAP, POP3, SMTP).

Here’s the sample for POP3:

// C#

using (Pop3 client = new Pop3())
{
    client.ConnectSSL("pop3.example.org");
    client.UseBestLogin("user", "password");

    Console.WriteLine("Supported methods:");

    foreach (var method in client.SupportedAuthenticationMethods())
    {
        Console.WriteLine(method.Name);
    }

    Console.WriteLine("Supports CramMD5:");

    bool supportsCramMD5 = client.SupportedAuthenticationMethods()
        .Contains(Pop3AuthenticationMethod.CramMD5);

    Console.WriteLine(supportsCramMD5);

    client.Close();
}
' VB.NET

Using client As New Pop3()
    client.ConnectSSL("pop3.example.org")
    client.UseBestLogin("user", "password")

    Console.WriteLine("Supported methods:")

    For Each method As Pop3AuthenticationMethod In client.SupportedAuthenticationMethods()
	    Console.WriteLine(method.Name)
    Next

    Console.WriteLine("Supports CramMD5:")

    Dim supportsCramMD5 As Boolean = client.SupportedAuthenticationMethods() _
        .Contains(Pop3AuthenticationMethod.CramMD5)

    Console.WriteLine(supportsCramMD5)

    client.Close()
End Using

Here’s the sample for SMTP:

// C#

using (Smtpclient = new Smtp())
{
    client.Connect("smtp.example.org");
    client.UseBestLogin("smtp", "password");

    Console.WriteLine("Supported methods:");

    foreach (var method in client.SupportedAuthenticationMethods())
    {
        Console.WriteLine(method.Name);
    }

    Console.WriteLine("Supports CramMD5:");

    bool supportsCramMD5 = client.SupportedAuthenticationMethods()
        .Contains(SmtpAuthenticationMethod.CramMD5);

    Console.WriteLine(supportsCramMD5);

    client.Close();
}
' VB.NET

Using client As New Smtp()
    client.Connect("smtp.example.org")
    client.UseBestLogin("user", "password")

    Console.WriteLine("Supported methods:")

    For Each method As SmtpAuthenticationMethod In client.SupportedAuthenticationMethods()
	    Console.WriteLine(method.Name)
    Next

    Console.WriteLine("Supports CramMD5:")

    Dim supportsCramMD5 As Boolean = client.SupportedAuthenticationMethods() _
        .Contains(SmtpAuthenticationMethod.CramMD5)

    Console.WriteLine(supportsCramMD5)

    client.Close()
End Using

Get supported server extensions (IMAP, POP3, SMTP)

Thursday, October 6th, 2011

Not every server supports same extensions. There are 3 classes that represent server extensions for each email protocol: ImapExtension, Pop3Extension and SmtpExtension. Those classes contain static properties with well-know extensions like: ImapExtension.Idle or ImapExtension.Sort or Pop3Extension.STLS etc.

You can use SupportedExtensions method to retrieve all protocol extensions supported by the server.

Get supported IMAP server extensions

// C#

using (Imap client = new Imap())
{
    client.ConnectSSL("imap.example.org");
    client.UseBestLogin("user", "password");

    Console.WriteLine("Supported extensions:");

    foreach (ImapExtension extension in client.SupportedExtensions())
    {
        Console.WriteLine(extension.Name);
    }

    Console.WriteLine("Supports IDLE:");

    bool supportsIdle = client.SupportedExtensions()
        .Contains(ImapExtension.Idle);

    Console.WriteLine(supportsIdle);

    client.Close();
}
' VB.NET

Using client As New Imap()
    client.ConnectSSL("imap.example.org")
    client.UseBestLogin("user", "password")

    Console.WriteLine("Supported extensions:")

    For Each extension As ImapExtension In client.SupportedExtensions()
	    Console.WriteLine(extension.Name)
    Next

    Console.WriteLine("Supports IDLE:")

    Dim supportsIdle As Boolean = client.SupportedExtensions() _
        .Contains(ImapExtension.Idle)

    Console.WriteLine(supportsIdle)

    client.Close()
End Using

For example Gmail produces following output:

Supported extensions:
IMAP4rev1
UNSELECT
IDLE
NAMESPACE
QUOTA
ID
XLIST
CHILDREN
X-GM-EXT-1
UIDPLUS
COMPRESS

Supports IDLE:
True

We take great care for the API to look similar for all protocols (IMAP, POP3, SMTP).

Get supported POP3 server extensions

// C#

using (Pop3 client = new Pop3())
{
    client.ConnectSSL("pop3.example.org");
    client.UseBestLogin("user", "password");

    Console.WriteLine("Supported extensions:");

    foreach (Pop3Extension extension in client.SupportedExtensions())
    {
        Console.WriteLine(extension.Name);
    }

    Console.WriteLine("Supports TOP:");

    bool supportsTop= client.SupportedExtensions()
        .Contains(Pop3Extension.Top);

    Console.WriteLine(supportsTop);

    client.Close();
}
' VB.NET

Using client As New Pop3()
    client.ConnectSSL("pop3.example.org")
    client.UseBestLogin("user", "password")

    Console.WriteLine("Supported extensions:")

    For Each extension As Pop3Extension In client.SupportedExtensions()
	    Console.WriteLine(extension.Name)
    Next

    Console.WriteLine("Supports TOP:")

    Dim supportsTop As Boolean = client.SupportedExtensions() _
        .Contains(Pop3Extension.Top)

    Console.WriteLine(supportsTop)

    client.Close()
End Using

Get supported SMTP server extensions

// C#

using (Smtpclient = new Smtp())
{
    client.Connect("smtp.example.org");
    client.UseBestLogin("smtp", "password");

    Console.WriteLine("Supported extensions:");

    foreach (SmtpExtension  extension in client.SupportedExtensions())
    {
        Console.WriteLine(extension.Name);
    }

    Console.WriteLine("Supports STARTTLS:");

    bool supportsStartTLS = client.SupportedExtensions()
        .Contains(SmtpExtension.StartTLS);

    Console.WriteLine(supportsStartTLS);

    client.Close();
}
' VB.NET

Using client As New Smtp()
    client.Connect("smtp.example.org")
    client.UseBestLogin("user", "password")

    Console.WriteLine("Supported extensions:")

    For Each extension As SmtpExtension In client.SupportedExtensions()
	    Console.WriteLine(extension.Name)
    Next

    Console.WriteLine("Supports STARTTLS:")

    Dim supportsStartTLS As Boolean = client.SupportedExtensions() _
        .Contains(SmtpExtension.StartTLS)

    Console.WriteLine(supportsStartTLS)

    client.Close()
End Using