Posts Tagged ‘VB.NET’

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.

Receive vCard business card

Saturday, March 3rd, 2012

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

IMail object exposes VCards collection that contains all vCard business cards that were found while parsing an email.

You can use both IMAP or POP3 protocol to download email from the server.

Here’s the simple sample showing how to process VCard business cards:

// C#

IMail email = new MailBuilder().CreateFromEml(client.GetMessageByUID(uid));

foreach (VCard vCard in email.VCards)
{

    Console.WriteLine("first name: " + vCard.Name.FirstName);
    Console.WriteLine("last name: " + vCard.Name.LastName);
    Console.WriteLine("full name: " + vCard.FullName);

    Console.WriteLine("email: " + vCard.Email);
    Console.WriteLine("work phone: " + vCard.WorkPhone);
    Console.WriteLine("home phone: " + vCard.HomePhone);

    if (vCard.WorkAddress != null)
    {
        Console.WriteLine(vCard.WorkAddress.PostOfficeBox);
        Console.WriteLine(vCard.WorkAddress.ApartmentNumber);
        Console.WriteLine(vCard.WorkAddress.Street);
        Console.WriteLine(vCard.WorkAddress.City);
        Console.WriteLine(vCard.WorkAddress.Region);
        Console.WriteLine(vCard.WorkAddress.PostalCode);
        Console.WriteLine(vCard.WorkAddress.Country);
    }
    if (vCard.HomeAddress != null)
    {
        //...
    }

    foreach (VCardPhone phone in vCard.Phones)
    {
        Console.WriteLine("phone: " + phone.Value);
    }
    foreach (VCardAddress address in vCard.Addresses)
    {
        Console.WriteLine("street: " + address.Street);
    }
    foreach (VCardEmail mail in vCard.Emails)
    {
        Console.WriteLine("email: " + mail.Value);
    }
}
' VB.NET

Dim email As IMail = New MailBuilder().CreateFromEml(client.GetMessageByUID(uid))

For Each vCard As VCard In email.VCards

	Console.WriteLine("first name: " + vCard.Name.FirstName)
	Console.WriteLine("last name: " + vCard.Name.LastName)
	Console.WriteLine("full name: " + vCard.FullName)

	Console.WriteLine("email: " + vCard.Email)
	Console.WriteLine("work phone: " + vCard.WorkPhone)
	Console.WriteLine("home phone: " + vCard.HomePhone)

	If vCard.WorkAddress IsNot Nothing Then
		Console.WriteLine(vCard.WorkAddress.PostOfficeBox)
		Console.WriteLine(vCard.WorkAddress.ApartmentNumber)
		Console.WriteLine(vCard.WorkAddress.Street)
		Console.WriteLine(vCard.WorkAddress.City)
		Console.WriteLine(vCard.WorkAddress.Region)
		Console.WriteLine(vCard.WorkAddress.PostalCode)
		Console.WriteLine(vCard.WorkAddress.Country)
	End If
			'...
	If vCard.HomeAddress IsNot Nothing Then
	End If

	For Each phone As VCardPhone In vCard.Phones
		Console.WriteLine("phone: " + phone.Value)
	Next
	For Each address As VCardAddress In vCard.Addresses
		Console.WriteLine("street: " + address.Street)
	Next
	For Each mail As VCardEmail In vCard.Emails
		Console.WriteLine("email: " + mail.Value)
	Next
Next

You can learn here how to send email with VCard.

Receive iCalendar meeting request

Monday, January 30th, 2012

Mail.dll .NET email component makes receiving iCalendar meeting request fairly easy.

IMail object exposes Appointments collection that contains all appointments that were found while parsing an email.

You can use both IMAP or POP3 protocol to download email from the server.

Here’s the simple sample showing how to process iCalendar appointments:

// C#

IMail email = new MailBuilder().CreateFromEml(client.GetMessageByUID(uid));

foreach (Appointment appointment in email.Appointments)
{
    if (appointment.Method == Method.Request)
    {
        // appointment was created
        string summary = appointment.Event.Summary;
        DateTime? start = appointment.Event.Start;
        DateTime? end = appointment.Event.End;
        string location = appointment.Event.Location;

        Console.WriteLine("{0} at {1} ({2}-{3})", summary, location, start, end);

        foreach (Participant participant in appointment.Event.Participants)
        {
            Console.WriteLine("Common name: " + participant.Cn);
            Console.WriteLine("Email: " + participant.Email);
            Console.WriteLine("Participation status: " + participant.Status);
        }
    }
    else if (appointment.Method == Method.Cancel)
    {
        // appointment was canceled
        Console.WriteLine("Event was cancelled: " + appointment.Event.UID);

    }
    else if (appointment.Method == Method.Reply)
    {
        // someone replied to the request
        foreach (Participant participant in appointment.Event.Participants)
        {
            if (participant.Status == ParticipationStatus.Accepted)
                Console.WriteLine("Event was accepted by: " + participant.Email);
            else if (participant.Status == ParticipationStatus.Declined)
                Console.WriteLine("Event was declined by: " + participant.Email);
        }

    }
}
' VB.NET

Dim email As IMail = New MailBuilder().CreateFromEml(client.GetMessageByUID(uid))

For Each appointment As Appointment In email.Appointments
	If appointment.Method = Method.Request Then
		' appointment was created
		Dim summary As String = appointment.[Event].Summary
		Dim start As System.Nullable(Of DateTime) = appointment.[Event].Start
		Dim [end] As System.Nullable(Of DateTime) = appointment.[Event].[End]
		Dim location As String = appointment.[Event].Location

		Console.WriteLine("{0} at {1} ({2}-{3})", summary, location, start, [end])

		For Each participant As Participant In appointment.[Event].Participants
			Console.WriteLine("Common name: " + participant.Cn)
			Console.WriteLine("Email: " + participant.Email)
			Console.WriteLine("Participation status: " + participant.Status)
		Next
	ElseIf appointment.Method = Method.Cancel Then
		' appointment was canceled

		Console.WriteLine("Event was cancelled: " + appointment.[Event].UID)
	ElseIf appointment.Method = Method.Reply Then
		' someone replied to the request
		For Each participant As Participant In appointment.[Event].Participants
			If participant.Status = ParticipationStatus.Accepted Then
				Console.WriteLine("Event was accepted by: " + participant.Email)
			ElseIf participant.Status = ParticipationStatus.Declined Then
				Console.WriteLine("Event was declined by: " + participant.Email)
			End If

		Next
	End If
Next

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

Extract plain text from HTML email

Tuesday, December 27th, 2011

Mail.dll MIME and email API’s may be used to get the plain-text body and HTML body from an email message.

If a message contains plain-text, no conversion is necessary. It’s simply a matter of using the Text property of IMail interface.

If however the email does not contain plain-text and only HTML content is available, GetTextFromHtml method may be used to convert the HTML to plain-text.

The internal conversion process is much more sophisticated than what can be accomplished with the simple regular-expression code. Converting HTML to plain text is much more than simply removing HTML tags from an HTML document.

Mail.dll contains full-blown HTML parser that handles script tags, comments, CDATA and even incorrect HTML.

The following C# and VB.NET code extracts plain-text from the HTML body of the email message:

// C#

IMail email = ...

string text = "";
if (email.IsText)
    text = email.Text;
else if (email.IsHtml)
    text = email.GetTextFromHtml();
Console.WriteLine(text);
' VB.NET

Dim email As IMail = ...

Dim text As String = ""
If email.IsText Then
    text = email.Text
ElseIf email.IsHtml Then
    text = email.GetTextFromHtml()
End If
Console.WriteLine(text)

You can also use GetBodyAsText method that returns body in plain text format (it uses IMail.Text property or GetTextFromHtml method).

// C#

IMail email = ...

string text = email.GetBodyAsText();
Console.WriteLine(text);
' VB.NET

Dim email As IMail = ...

Dim text As String = email.GetBodyAsText()
Console.WriteLine(text)