Sending Authenticated Emails in .NET 2.0

Author Xavier Larrea

 

Sending e-mails in the .NET Framework 2.0 is about the same as in version 1.x. There are just a couple of variations. First, all the functionality is within the new System.Net.Mail namespace. The System.Web.Mail namespace, wich was used in the 1.x frameworks is now considered obsolete.

Lets get right to the code. It's really straight forward and self explanatory:

MailMessage oMsg = new MailMessage();

// Set the message sender
oMsg.From = new MailAddress("xavier@devel.oping.net", "Xavier Larrea");

// The .To property is a generic collection,
// so we can add as many recipients as we like.
oMsg.To.Add(new MailAddress("fox@foxcorp.org","John Doe"));

// Set the content
oMsg.Subject = "My First .NET email";
oMsg.Body = "Test body - .NET Rocks!";
oMsg.IsBodyHtml = true;

SmtpClient oSmtp = new SmtpClient("smtp.myserver.com");

//You can choose several delivery methods.
//Here we will use direct network delivery.
oSmtp.DeliveryMethod = SmtpDeliveryMethod.Network;

//Some SMTP server will require that you first
//authenticate against the server.

NetworkCredential oCredential = new NetworkCredential("myusername","mypassword");
oSmtp.UseDefaultCredentials = false;
oSmtp.Credentials = oCredential;

//Let's send it already
oSmtp.Send(oMsg);

Very easy, right? Remember always to use the Try-Catch block when sending emails because lot of things can cause an exception: bad email addresses, authentication errors, network failure, etc.

I hope you find this code useful. Happy coding!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值