Send email using fluent interface
// C# version using Fluent = Limilabs.Mail.Fluent; Fluent.Mail.Html(@"Html with an image: <img src=""cid:lena"" />") .AddVisual(@"c:lena.jpeg").SetContentId("lena") .AddAttachment(@"c:tmp.doc").SetFileName("document.doc") .To("to@mail.com") .From("from@mail.com") .Subject("Subject") .UsingNewSmtp() .Server("smtp.example.org") .WithSSL() .WithCredentials("user", "password") .Send();
' VB.NET version Imports Fluent = Limilabs.Mail.Fluent; Fluent.Mail.Html("Html with an image: <img src=""cid:lena"" />") _ .AddVisual("c:lena.jpeg").SetContentId("lena") _ .AddAttachment("c:tmp.doc").SetFileName("document.doc") _ .[To]("to@mail.com") _ .From("from@mail.com") _ .Subject("Subject") _ .UsingNewSmtp() _ .Server("smtp.example.org") _ .WithSSL() _ .WithCredentials("user", "password") _ .Send()
Fluent interface for creating and sending emails was added to Mail.dll as an additional feature.
You can still use MailBuilder class to create emails.
Note that error handling code was removed for simplicity, you should use try…catch block when sending.
If your server does not require authentication or SSL simply skip WithSSL and WithCredentials methods:
// C# version Mail.Text("Hi there") .Subject("Hi") .To("to@mail.com") .From("from@example.org") .UsingNewSmtp() .Server("smtp.example.org") .Send();
' VB.NET version Mail.Text("Hi there") _ .Subject("Hi") _ .[To]("to@mail.com") _ .From("from@example.org") _ .UsingNewSmtp() _ .Server("smtp.example.org") _ .Send()
Same code using MailBuilder:
// C# version MailBuilder builder = new MailBuilder(); builder.Text = "Hi there"; builder.Subject = "Hi"; builder.To.Add(new MailBox("to@mail.com")); builder.From.Add(new MailBox("from@example.org")); IMail email= builder.Create(); using(Smtp smtp = new Smtp()) { smtp.Connect("smtp.example.org"); // or ConnectSSL // smtp.UseBestLogin("user", "password"); smtp.SendMessage(email); smtp.Close(); }
' VB.NET version Dim builder As New MailBuilder() builder.Text = "Hi there" builder.Subject = "Hi" builder.[To].Add(New MailBox("to@mail.com")) builder.From.Add(New MailBox("from@example.org")) Dim emailAs IMail = builder.Create() Using smtp As New Smtp() smtp.Connect("smtp.example.org") ' or ConnectSSL ' smtp.UseBestLogin("user", "password") smtp.SendMessage(email) smtp.Close() End Using
You can also reuse existing Smtp connection to send multiple emails using fluent interface:
// C# version using(Smtp smtp = new Smtp()) { smtp.Connect("smtp.example.org"); // or ConnectSSL smtp.UseBestLogin("user", "password"); Mail.Text("Hi there") .Subject("Hi") .To("to@mail.com") .From("from@example.org") .Send(smtp); // Send more emails here... smtp.Close(); }
' VB.NET version Using smtp As New Smtp() smtp.Connect("smtp.example.org") ' or ConnectSSL smtp.UseBestLogin("user", "password") Mail.Text("Hi there") _ .Subject("Hi") _ .[To]("to@mail.com") _ .From("from@example.org") _ .Send(smtp) ' Send more emails here... smtp.Close() End Using