Sending Email with System.Net.Mail

.NET 2.0 includes much richer Email API support within the System.Net.Mail code namespace.  I've seen a few questions from folks wondering about how to get started with it.  Here is a simple snippet of how to send an email message from “sender@foo.bar.com” to multiple email recipients (note that the To a CC properties are collections and so can handle multiple address targets):

 

MailMessage message = new MailMessage();

message.From = new MailAddress("sender@foo.bar.com");

 

message.To.Add(new MailAddress("recipient1@foo.bar.com"));

message.To.Add(new MailAddress("recipient2@foo.bar.com"));

message.To.Add(new MailAddress("recipient3@foo.bar.com"));

 

message.CC.Add(new MailAddress("carboncopy@foo.bar.com"));

message.Subject = "This is my subject";

message.Body = "This is the content";

 

SmtpClient client = new SmtpClient();

client.Send(message);

 

System.Net.Mail reads SMTP configuration data out of the standard .NET configuration system (so for ASP.NET applications you’d configure this in your application’s web.config file).  Here is an example of how to configure it:

 

  <system.net>

    <mailSettings>

      <smtp from="test@foo.com">

        <network host="smtpserver1" port="25" userName="username" password="secret" defaultCredentials="true" />

      </smtp>

    </mailSettings>

  </system.net>

 

Hope this helps,

 

Scott

 

P.S. Many thanks to Federico from my team for putting the above sample together.

 

Published Saturday, December 10, 2005 9:00 PM by ScottGu

Comments

# re: Sending Email with System.Net.Mail

Sunday, December 11, 2005 1:01 AM by scottgu
That is a very cool sample Mike!

# re: Sending Email with System.Net.Mail

Sunday, December 11, 2005 6:29 AM by Manu
I haven't checked the new api, but is it possible to send messages where you can include the person name and the email address? For example:

From: Anonymous sender <sender@foo.bar.com>
To: Recipient 1 <recipient1@foo.bar.com>

In 1.1 this was a nightmare.

# re: Sending Email with System.Net.Mail

Sunday, December 11, 2005 6:30 AM by Andrey Skvortsov
When you will be using generic avalon serialization mechanism for config files?

Thanks.

# re: Sending Email with System.Net.Mail

Sunday, December 11, 2005 11:58 AM by karl
Why are the properties of MailAddress read-only? This makes it hard to load email templates with placeholders "{siteAdmin}", and replace them at runtime.

Karl

# re: Sending Email with System.Net.Mail

Sunday, December 11, 2005 1:19 PM by scottgu
Hi Manu,

The MailAddress class takes both an email address and a displayname as constructor arguments. I believe this second argument allows you to control the name that shows up (for example: Scott Guthrie <scottgu@microsoft.com>) and provides what you are after.

Hope this helps,

Scott

# re: Sending Email with System.Net.Mail

Sunday, December 11, 2005 1:22 PM by scottgu
Hi Andrey,

We don't have plans to use XAML (the avalon serialization format) for the configuration file format anytime soon.

XAML is about serializing object graphs, and the content within .config files is very different. Specifically, .config files represent configuration data with specific semantics (for example: inherited collections, lockdown semantics, etc) that would be difficult/ugly to display as an object-graph.

Hope this helps,

Scott

# re: Sending Email with System.Net.Mail

Sunday, December 11, 2005 1:27 PM by scottgu
Hi Karl,

The MailAddress class uses the immutable pattern -- so once the instance is created, it can't be modified (there are some benefits to this pattern -- since among other things it can help a lot with threading, since there are no lock contention issues).

The collection it gets placed into on the Message type (the to, from, cc collections) can be modified though. So you can always remove an existing MailAddress instance from one of those, and then create a new MailAddress class that replaces it with modified values.

Hope this helps,

Scott

# re: Sending Email with System.Net.Mail

Monday, December 12, 2005 4:24 AM by Andrey Skvortsov
I always thought that "configuration data" is specialized "object graph"'s serialization format.I don't know what you means under "inherited collections" but all other semantics can be expressed easily in XAML IMHO.That's XAML is for-it's always nice to see how we all write config xml schemas only to express config specific objects instantiation formats;-)
If I can't properly describe config of app in XAML it means something wrong with XAML itself-not with generic idea.Think youself for a moment-I can describe "workflow" in XAML but not config.Sounds funny,isn't it?

Thanks a lot.

# re: Sending Email with System.Net.Mail

Monday, December 12, 2005 10:12 AM by Buddy Lindsey
Thank you I have been trying to figure this out off and on for a week now.

# re: Sending Email with System.Net.Mail

Monday, December 12, 2005 12:18 PM by scottgu
Hi Andrey,

Consider the below behavior, where you have one collection of assemblies defined in a root web.config:

<assemblies>
<add assembly="assemblya.dll"/>
<add assembly="assemblyb.dll"/>
<add assembly="assemblyc.dll"/>
</assemblies>

and then have a web.config file below it that inherits these values, and then removes one of them and adds another:

<assemblies>
<remove assembly="assemblyb.dll"/>
<add assembly="assemblyd.dll"/>
</assemblies>

This style of collection behavior is super-common in the configuration system. The XML syntax represents less object types, and more imperative instructions to build up collection data.

Expressing these semantics through an object serialization format (including XAML) ends up being very difficult.

Hope this explains the issue,

Scott

# re: Sending Email with System.Net.Mail

Thursday, December 15, 2005 4:31 AM by Andrey Skvortsov
But how about workflow Actions?I believe that's not inheritance per se but simply add/remove-modify already existent collection Actions.

Regards.

# re: Sending Email with System.Net.Mail

Friday, December 16, 2005 12:35 PM by David Droman
I can't seem to get to be able to set the "Return-Path" in a message with asp.net 2.0 ... anybody tried this? (i end up with two return-path settings in the message headers.

# re: Sending Email with System.Net.Mail

Wednesday, December 21, 2005 11:36 AM by Eber Irigoyen
that's way too easy... any way to encrypt the password?

# re: Sending Email with System.Net.Mail

Wednesday, December 28, 2005 11:44 PM by duane
Hi,I don't know why i can't send mail successed, i use the same code for my application, who has any good idea for me? thanks.

# re: Sending Email with System.Net.Mail

Friday, December 30, 2005 4:49 AM by croix
hey, i need to send html content through email... how can it be done with the code u showed??

# re: Sending Email with System.Net.Mail

Wednesday, January 4, 2006 3:29 PM by Curt Deyrup
It seems that, if you have multiple addressees, you must put the first one into the statement that instantiates the New message (because an address.to is a required parameter that can't be referenced until the message is instantiated), and then build an address collection by adding all the others, with message.to.add, in a subsequent series of statements (or via a loop), as follows:

Dim addressFrom As New MailAddress("cdeyrup@co.bergen.nj.us")
Dim addressto As New MailAddress("cdeyrup@co.bergen.nj.us")
Dim msg As New MailMessage(addressFrom, addressto)
msg.To.Add(New MailAddress("curtdeyrup2@aol.com"))
msg.To.Add(New MailAddress("adacosta@co.bergen.nj.us"))
msg.To.Add(New MailAddress("dfrank@co.bergen.nj.us"))

Isn't this a little clunky? The lack of explanatory detail on the use of this new version of the Mail namespace is fairly stunning, in light of the fact that it was totally rewritten, apparently repeatedly rewritten, and none of the old stuff works.

# re: Sending Email with System.Net.Mail

Wednesday, May 31, 2006 11:54 PM by Joel
Hi Scott,
Is it possible to set a "friendly" name in the <smtp from="test@foo.com"> section?

-Joel

# re: Sending Email with System.Net.Mail

Thursday, June 1, 2006 1:22 AM by ScottGu
Hi Joel,

That is a good question -- and unfortunately one I'm not really sure of.  :-(

Sorry!

Scott

# re: Sending Email with System.Net.Mail

Tuesday, June 6, 2006 6:06 AM by ross2pak
hi,

i tried the code above however I get this error:

System.Net.Mail.SmtpException: Failure sending mail. The requested service provider could not be loaded or initialized. I am using my machine as the smtp server. When I use the system.web.mail in previous version of .net, it works just fine. please help. =)

# re: Sending Email with System.Net.Mail

Tuesday, June 6, 2006 11:09 AM by ScottGu
Hi Ross,

I belive the connection configuration for the two APIs are different -- so if it is working in one but not the other that could be the reason.

I'd recommend looking up information on the mail configuration in the <system.net> section for how to configure the SMTP server location.  This controls the System.Net.Mail location.

Hope this helps,

Scott

# re: Sending Email with System.Net.Mail

Wednesday, June 7, 2006 11:28 AM by Sai Giridhar K
Hi,

I get following error while sending (client.(Send(Message)) mail.

Mailbox name not allowed. The server response was: sorry, Authentication failed or timed out. Please do get messages first to authenticate yourself.(#4.4.3)

I have not configured SMTP service. I have Norton Antivirus 2003 scanning incoming & outgoing mails. The MS Outlook is closed.

What I have noted is when MS Outlook is open and I use same from address as that configured in MS Outlook mail goes. It won't go if I use a different from address.

Can you help?

Thanks,
Sai Giridhar K

# re: Sending Email with System.Net.Mail

Thursday, June 8, 2006 1:29 PM by ScottGu
Hi Sai,

Outlook is actually unrelated to teh System.Net mail APIs.  What you need to-do is make sure that you have a SMTP server configured in your web.config and that your web-server has access to contact it.

Hope this helps,

Scott

# re: Sending Email with System.Net.Mail

Monday, July 31, 2006 11:05 AM by Esben
Is there a nead way, other than making a sql call, to retrieve all users emailadresses in the asp.net autocreated database.

# re: Sending Email with System.Net.Mail

Monday, July 31, 2006 9:33 PM by ScottGu

Hi Esben,

Membership.GetAllUsers() will return a collection of users in the Membership database.  You can then loop through this and retrieve the email address of each user.

Hope this helps,

Scott

# re: Sending Email with System.Net.Mail

Saturday, August 5, 2006 3:15 PM by Prem
You guys are awesome!

# re: Sending Email with System.Net.Mail

Friday, August 11, 2006 2:36 AM by ScottGu

Hi Kemal,

Have you configured your local SMTP Email Service (you can pull up its properties via the IIS admin tool I believe).  You need to point the SMTP service at your mail router for it to in turn send the mail to the final destination.  Otherwise it is probably just queing up on disk in the SMTP Server.

Hope this helps,

Scott

# re: Sending Email with System.Net.Mail

Friday, August 18, 2006 2:06 PM by Aru J
Hi Scott, I am using system.net.mail to send a simple email. I am in my company intranet and i'm using my company exchange server as my smtp host. when i try to send the mail, i get an error "Failure sending mail" and the inner exception tells "Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.". Thanks, Aru

# re: Sending Email with System.Net.Mail

Friday, August 18, 2006 5:07 PM by ScottGu
Hi Aru, I'd check two things: 1) Do you have a firewall setup that might be preventing access on that port? 2) Is the SMTP service started on the address you are pointing at? thanks, Scott

# re: Sending Email with System.Net.Mail

Saturday, August 19, 2006 6:51 AM by Aru
Scott, I think i am behind a firewall. In that case how should i send a mail using my credentials. thanks Aru

# re: Sending Email with System.Net.Mail

Tuesday, August 22, 2006 7:33 PM by ScottGu

Hi Aru,

It will work if your company is behind a firewall.  The issue is if you are running a personal firewall on your local system or on the system that has the mail server installed (for example: if you have Windows XP SP2 installed).  In this case it will probably block requests from your app to connect and send mail to it.

You should configure your personal firewall to allow this port in order to make it work.

Hope this helps,

Scott

# re: Sending Email with System.Net.Mail

Sunday, August 27, 2006 6:25 PM by Tom
Scott, I have successfully sent an email with two mime types (plain text and html) to my Outlook email address… My question is: Is there a way to avoid the email from being sent directly to the ‘Junk E-mail’ folder? For example – when I receive an email from Microsoft (Exploring Windows and/or TechNet Flash) or from CodeProject (in HTML format), it does go to the Inbox, and of course I would right-click in the Outlook message to ‘Download Pictures” and so on, but I am unable to achieve the same results… Any suggestions??? Regards, Tom.

# re: Sending Email with System.Net.Mail

Tuesday, August 29, 2006 12:32 AM by ScottGu

Hi Tom,

The junk mail detection is done by your email client -- and so is independent of how you sent the email.

I suspect what is happening is that your message is somehow triggering the junk mail detection in your client because of its content.

Hope this helps,

Scott

# re: Sending Email with System.Net.Mail

Thursday, August 31, 2006 9:43 AM by Dev
Hi, I am getting an error while sending mail in HTML format . saying error could not access object CDO.Message. its an internal company server and was working fine for all these days. if i send it in text format all goes fine. I really dont know whats the problem. i am using ASP.net c#. Any help will be greatly appreciated.

# re: Sending Email with System.Net.Mail

Thursday, August 31, 2006 10:31 PM by ScottGu

Hi Dev,

If you are getting a CDO.Message error, then you aren't using the System.Net.Mail namespace above, but rather the older System.Web.Mail API.

Have you tried using the new .NET 2.0 API above?

Thanks,

Scott

# re: Sending Email with System.Net.Mail

Thursday, August 31, 2006 10:33 PM by ScottGu

Hi Derik,

Can you check to see whether you have a personal firewall enabled on your machine (note that Windows XP SP2 does this by default).  That could be the reason for the connect failure.

Hope this helps,

Scott

# re: Sending Email with System.Net.Mail

Friday, September 8, 2006 7:04 AM by smtp mail not working
i have configure the smtp but timeout error is displying? guru

# re: Sending Email with System.Net.Mail

Friday, September 15, 2006 10:55 AM by llong
i also have the same error - Operation timed out. I don't understand what happened. I have been able to successfully email connecting to our remote server for months, now it quit working all of the sudden. i can send email using the localhost, but i can send email when i try to connect to the smtp on the mail server.

# re: Sending Email with System.Net.Mail

Sunday, September 17, 2006 6:48 PM by Laila
hi, I tried the code in your video example, but when I click on "finish button", nothing happens, & I don't receive email *I think the problem is in the server name this the code: ///////////////////////////////// Imports System.Net.Mail Partial Class _Default Inherits System.Web.UI.Page Protected Sub Wizard1_FinishButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles Wizard1.FinishButtonClick SendMail(txtEmail.Text, txtComments.Text) End Sub Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate If txtComments.Text.Length > 10 Then args.IsValid = False Else args.IsValid = True End If End Sub Private Sub SendMail(ByVal from As String, ByVal body As String) Dim mailServerName As String = "www.yahoo.com" Dim message As MailMessage = New MailMessage(from, "Laila@yahoo.com", "feedback", body) Dim mailClient As SmtpClient = New SmtpClient mailClient.Host = mailServerName mailClient.Send(message) message.Dispose() End Sub End Class

# re: Sending Email with System.Net.Mail

Tuesday, September 26, 2006 8:33 PM by Oscar
Is it possible to Create a Class that stores the Mail setting instead of using the Web.Config?

# re: Sending Email with System.Net.Mail

Wednesday, September 27, 2006 12:34 AM by ScottGu

Hi Oscar,

The SmtpClient class has properties for things like the host address that you can set programmaticlaly.  This avoids you having to configure anything in your web.config file.

Hope this helps,

Scott

# re: Sending Email with System.Net.Mail

Saturday, September 30, 2006 2:06 PM by ScottGu

Hi Nisar,

Some email clients are picky about how they handle style information.  You might find that you want/need to use inline styles instead to work everywhere.

Hope this helps,

Scott

# re: Sending Email with System.Net.Mail

Saturday, September 30, 2006 2:59 PM by Nisar Khan
Thanks Scott for your valuable input

# re: Sending Email with System.Net.Mail

Monday, October 2, 2006 4:14 PM by Nisar Khan
>>Scott said: >>Some email clients are picky about how they >>handle style information. You might find >>that you want/need to use inline styles >>instead to work everywhere. is that the only way to work out? some how I'm not very comfortable using in-line style-sheet, you know the reason, if we decided to change the font color or style then I end-up changing all my .htm files which is around 10 can you think of anything please? :) Thanks

# re: Sending Email with System.Net.Mail

Monday, October 2, 2006 4:54 PM by Nisar Khan
ignore my last request. I never thought of hard coding the css into the file :)

# re: Sending Email with System.Net.Mail

Wednesday, October 11, 2006 4:32 PM by Mimi
Hi Scott, I had a question about the SendAsync() method of the SmtpClient class. When I send email from my ASPX page is it necessary to set the Page Async attribute to use this? MG

# re: Sending Email with System.Net.Mail

Wednesday, October 11, 2006 11:56 PM by ScottGu

Hi Mimi,

Nope -- that isn't required here.  The reason is that the Page doesn't need to wait on sending the mail - so it can complete immediately.

Hope this helps,

Scott

# re: Sending Email with System.Net.Mail

Thursday, October 12, 2006 11:23 PM by Mimi
Hi Scott, Thanks for replying but I could not find a way to make SMTPClient.SendAsync() work without setting . Without this setting, I get this error message: "Asynchronous operations are not allowed in this context. Page starting an asynchronous operation has to have the Async attribute set to true and an asynchronous operation can only be started on a page prior to PreRenderComplete event."

# re: Sending Email with System.Net.Mail

Tuesday, October 17, 2006 10:24 AM by ScottGu

Hi Lee,

My guess is that if it is silently failing, then what is happening is that the mail is being delivered to the mail box folder on the local SMTPServer, but isn't being forwarded along.

Can you check your local SMTPServer to see if this might be the case?  There is typically a folder where all mails to be sent are saved - is there anything in it?

thanks,

Scott

# re: Sending Email with System.Net.Mail

Tuesday, October 17, 2006 10:53 AM by ScottGu

Hi Param,

You need to have access to a SMTP Server that will support forwarding the mail to the correct location.

Unfortunately Yahoo doesn't allow remote users to-do this with their mail servers (for SPAM protection reasons).

I'd recommend talking with your ISP or DSL/Cable-Modem provider to see if they have an SMTP server you could use.

Hope this helps,

Scott

# re: Sending Email with System.Net.Mail

Tuesday, October 17, 2006 5:56 PM by Lee Fear
oops I was wrong! My message appears in the Queue folder in c:/inetpub/mailroot. It must get cleared on close down or after a time period as it only appeared after sending another smtpmail.

# re: Sending Email with System.Net.Mail

Wednesday, October 18, 2006 3:56 PM by Lee Fear
I have found that if I send to a hotmail address my mail gets lost but if I send to other addresses it gets to the destination. Strangely though it gets to the hotmail address if I send from .net 1.1

# re: Sending Email with System.Net.Mail

Monday, October 23, 2006 2:38 PM by VB
can i set \Pickup directory if i use my company's exchange server? if not what wold be my option? (SmtpDeliveryMethod)

# re: Sending Email with System.Net.Mail

Wednesday, October 25, 2006 12:49 AM by Rahul
How to find RelayServer name ,port number user name and password PLZ provide me the solution Thanks in advance Rahul

# re: Sending Email with System.Net.Mail

Thursday, October 26, 2006 1:11 AM by ScottGu

Hi kee,

Do you have the SMTP service running?

Thanks,

Scott

# re: Sending Email with System.Net.Mail

Friday, October 27, 2006 3:04 AM by Satish
when i try to send a mail i get this error i am using VS 2.0 IIS 6.0 System.Net.Mail.SmtpFailedRecipientException: Mailbox name not allowed. The server response was: Attack detected. at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception) at System.Net.Mail.SmtpClient.Send(MailMessage message) at _Default.Page_Load(Object sender, EventArgs e)

# re: Sending Email with System.Net.Mail

Saturday, October 28, 2006 12:37 PM by ScottGu

Hi Satish,

It sounds like your mail server isn't allowing remote connections, which is probably why the mail isn't going through.

Hope this helps,

Scott

# re: Sending Email with System.Net.Mail

Sunday, October 29, 2006 9:01 PM by Dominic Pettifer
Is it possible to specify multiple SMTP servers in the web.config file under the mailSettings element? I've tried doing this... But it complains that smtp element can only be used once. Any ideas? Cheers!

# re: Sending Email with System.Net.Mail

Tuesday, October 31, 2006 1:00 AM by ScottGu

Hi Dominic,

Unfortunately I think you can only have one SMTP server registered.

Sorry!

Scott

# re: Sending Email with System.Net.Mail

Thursday, November 2, 2006 3:29 PM by Janet
In case someone else has the problem, I found the solution: My control had an onclick event, and the sub called had this: protected sub btnClick_Click(ByVal sender as object, ByVal e as EventArgs) Handles btnClick.Click ....blah email End Sub Removed the "Handles btnClick.Click" and everything works ducky now....

# re: Sending Email with System.Net.Mail

Saturday, November 4, 2006 7:06 PM by Ryan

OK, I have read over all the topics here and have not stumbled accross an answer to a question I have, if anyone would be so kind at to try and figure it out.

I am using

Attachment.CreateAttachmentFromString(faxbody, "WebPage.html", null,);

The attachment works fine ans is attached to the email. But the body of the emai also has the html code from the page that was streamed???  Does anyone know why?  This one is killing me.

Thanks

Ryan

# Sending Email with System.Net.Mail

Tuesday, November 7, 2006 12:05 AM by chaman
Hi, i want to send a mail which accepts the smtp server name, recepient's address and sender's address, takes the subject and the body in UI ( asp.net web page) from user. how do i do it?

# Sending Email with System.Net.Mail

Tuesday, November 7, 2006 12:05 AM by chaman
Hi, i want to send a mail which accepts the smtp server name, recepient's address and sender's address, takes the subject and the body in UI ( asp.net web page) from user. how do i do it?

# re: Sending Email with System.Net.Mail

Sunday, November 12, 2006 10:52 PM by Prashant
Hi Lee, Did you find a solution to the following problem? Thanks in advance. --quote I have found that if I send to a hotmail address my mail gets lost but if I send to other addresses it gets to the destination. Strangely though it gets to the hotmail address if I send from .net 1.1 --unquote

# re: Sending Email with System.Net.Mail

Tuesday, November 21, 2006 11:31 AM by ScottGu

Hi Rob,

I hadn't actually heard of this issue before.  If you want to send me email about it, I'd be happy to connect you with someone on the networking team to see if they know of it and/or have a fix.

Thanks,

Scott

# re: Sending Email with System.Net.Mail

Wednesday, November 22, 2006 3:36 PM by ShawnP

Hello,

I cannot seem to send to multiple recipients successfully.  Everything I try only manages to send to the first person of the 2 that I want to send the email to.

I have tried having both emails in a comma delimited string.

mail.to.add(new mailaddress("sp@aa.com, tp@aa.com")

I have also tried adding them separately.

mail.to.add(new mailaddress("sp@aa.com")

mail.to.add(new mailaddress("tp@aa.com")

Then I tried what Curt recommended, adding the first person in the To field while instantiating the mail object.  Then adding the second person separately using the same call as above.  Still didn't work.

No matter what I do, only sp@aa.com gets the email.  If I reverse the recipients, then tp@aa.com gets the email, so its clearly only the first recipient that is being sent to.

Any help please??  I can't figure this out at all!

# re: Sending Email with System.Net.Mail

Wednesday, November 22, 2006 5:05 PM by Brett

This is what I have come up with in VS2005 to send email.

This fully supports all of my 1.0 and 1.1 appliications as well since I do not have to worry about the comma, semicolon issue between 1x and 2.0

Let me know if this is helpful.

Public Function SendEMail(ByVal strFrom As String, ByVal strTo As String, ByVal strCC As String, ByVal strBcc As String, ByVal strSubject As String, ByVal strBody As String, Optional ByVal strAttachment As String = "", Optional ByVal strBodyType As String = "") As String

           Try

               Dim MailMsg As New MailMessage

               MailMsg.From = New MailAddress(strFrom)

               If strTo <> "" Then

                   Dim strToArray As String()

                   strToArray = strTo.Split(";")

                   Dim ToInt As Integer = strToArray.Length

                   Dim Tocount As Integer = 0

                   While Tocount < ToInt

                       MailMsg.To.Add(New MailAddress(strToArray(Tocount)))

                       Tocount = Tocount + 1

                   End While

               Else

                   Return "error; No To Adress Specified"

               End If

               If strCC <> "" Then

                   Dim strccArray As String()

                   strccArray = strCC.Split(";")

                   Dim ccInt As Integer = strccArray.Length

                   Dim ccCount As Integer = 0

                   While ccCount < ccInt

                       MailMsg.CC.Add(New MailAddress(strccArray(ccCount)))

                       ccCount = ccCount + 1

                   End While

               End If

               If strBcc <> "" Then

                   Dim strBccArray As String()

                   strBccArray = strBcc.Split(";")

                   Dim BccInt As Integer = strBccArray.Length

                   Dim BccCount As Integer = 0

                   While BccCount < BccInt

                       MailMsg.Bcc.Add(New MailAddress(strBccArray(BccCount)))

                       BccCount = BccCount + 1

                   End While

               End If

               MailMsg.Subject = strSubject

               MailMsg.Body = strBody

               If strBodyType <> "" Then

                   Select Case LCase(strBodyType)

                       Case "html"

                           MailMsg.IsBodyHtml = True

                       Case "text"

                           MailMsg.IsBodyHtml = False

                   End Select

               End If

               If strAttachment <> "" Then

                   Dim strAttachmentArray As String()

                   strAttachmentArray = strAttachment.Split(";")

                   Dim AttachmentInt As Integer = strAttachmentArray.Length

                   Dim AttachmentCount As Integer = 0

                   While AttachmentCount < AttachmentInt

                       MailMsg.Attachments.Add(New Attachment(strAttachmentArray(AttachmentCount)))

                       AttachmentCount = AttachmentCount + 1

                   End While

               End If

               Dim MailServerName As String = "PutYourServerNameHere"

               Dim mSmtpClient As New SmtpClient

               mSmtpClient.Host = MailServerName

               Try

                   mSmtpClient.Send(MailMsg)

               Catch objException As Exception

                   SendNotificationMsg = objException.Message

               End Try

               mSmtpClient = Nothing

               For Each aAttach As Attachment In MailMsg.Attachments

                   aAttach.Dispose()

               Next

               MailMsg.Attachments.Dispose()

               MailMsg.Dispose()

               MailMsg = Nothing

           Catch ex As Exception

               Return "error"

           End Try

           Return "Sent"

       End Function

# re: Sending Email with System.Net.Mail

Thursday, November 30, 2006 6:35 AM by Arnout

Hi,

everything works smoothly, except when I add a special character like é or à or è , etc in my recipient e-mail address.

Error returned :

The specified string is not in the form required for an e-mail address.

Any solution ?

Greets,

Arnout Symoens

# re: Sending Email with System.Net.Mail

Monday, December 4, 2006 10:44 AM by Sam

Hi

I have used system.web.mail in .net 1.1 with no problems, also xp_smtp_sendmail in SQL Server 2000. However, both system.net.mail and the new Database Mail in SQL Server 2005 fail with the same error

Exception Message: Could not connect to mail server. (No connection could be made because the target machine actively refused it).)

I have never had to supply credentials when using the old versions, so what's the problem now?

I am using my company's smtp server at head office which is remote from me, but as I say, it works perfectly with both system.web.mail and xp_smtp_sendmail.

Many thanks

Sam Evans

# re: Sending Email with System.Net.Mail

Tuesday, December 5, 2006 11:05 AM by Chandan

Hi,

IS there way in your code to know if the reader has read an email or no. I tried  Disposition Notification but it only works for outlook not for yahoo hotmail etc.....Please let me knw

# re: Sending Email with System.Net.Mail

Wednesday, December 6, 2006 12:04 AM by ScottGu

Hi Chandan,

Unfortunately there is no easy way to get a confirmation receipt.

Sorry about that,

Scott

# re: Sending Email with System.Net.Mail

Thursday, December 14, 2006 11:50 AM by Russ

I am attempting to send an email message with frustrating results.  The problem is that the message will not send immediately; it only sends when I exit the application.  This is happening in a larger app, but I have duplicated in a very simple example.

Created new Windows Form Application in VB2005.  Dropped a button into the middle of the form with the following code:

Imports System.Net.Mail

Public Class Form1

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

       Try

           Dim mailSMTPClient As New SmtpClient("mailserver")

           Dim mailFromAddress As New MailAddress("test@domain.com")

           Dim mailToAddress As New MailAddress("user@domain.com")

           Dim mailMessage As New MailMessage(mailFromAddress, mailToAddress)

           With mailMessage

               .Subject = "Test"

               .Body = "Hello!  This is a test."

           End With

           With mailSMTPClient

               .DeliveryMethod = SmtpDeliveryMethod.Network

               .Send(mailMessage)

           End With

       Catch ex As Exception

           MsgBox("Exception: " & ex.Message)

       End Try

   End Sub

End Class

The example couldn't be more simple, but I get the same result.  The message will not send until I exit the application.

What am I missing?

Thanks in advance for any help.

# re: Sending Email with System.Net.Mail

Wednesday, December 20, 2006 4:59 AM by Eti

System.web.mail works every time from the same project without changing any configuration settings, despite warnings that System.web.mail is obsolete.

I have now written a new sendMail procedure with system.net.mail, which failed with

Mailbox unavailable. The server response was: 5.7.1 Unable to relay...

I have made changes to the smtp server on iis, which I shouldn't have had to. Now it sends the messages but I can see .eml files in C:\Inetpub\mailroot\queue\ going nowhere!

What gives? How do we use System.net.mail the way System.web.mail worked.

Changing iis smtp settings and messing about with smtpHost (whether localhost or 127.0.0.1) should be optional.

Thanks

Eti

# re: Sending Email with System.Net.Mail

Wednesday, December 20, 2006 3:43 PM by Russ

In case anyone is interested, I tracked down the cause of the problem I mentioned above with system.net.mail not sending outgoing messages until the application ends.

It turned out being related to Symantec AntiVirus (Full version 9.0.0.338) that I have running on my machine.  I was able to eliminate the problem by turning off the "Internet E-Mail Auto-Protect" feature.  Turning it back on resulted in the same send delay.  Using the system.web.mail namespace does not exhibit this problem (despite the IDE's warnings about it being obsolete.)

I would love to use the system.net.mail namespace, but I can't assume client workstations will not have Symantec Anti-Virus running.  

# re: Sending Email with System.Net.Mail

Thursday, December 21, 2006 9:21 AM by deen mohammad

Scott and Evryone,

Please do help me.. not too much asp.net techies here in KSA and i am coming from a cfm environment.

my problem is that I have a formview that I use for inserting data to a DB. after insertion it sends the form BUT i dont know how to embed sent the content of the user's input within the formview. i am using one page only inserting and sending.. thanks..

# re: Sending Email with System.Net.Mail

Tuesday, January 2, 2007 12:52 AM by Rajesh Yadav

Hi all,

Please tell me what this namespace

System.Net.Mail.SmtpFailedRecipientException

checks so it throws exceptions. i.e what to want to confirm that in addition to dns checking ,is it also checks that, that host is not in the smtp server database.

Moreover I want to know the specific record name the mail server validates the email Id of the receipent.

e.g through MX records we get the mail server name but from where mail server validate the host of his domain.

Please do help me or guide me how i validate the email id of my receipent. (Note : not validate the dns or mail server but email on mail server )

Thanks in advance for all your advices and help.

Rajesh Yadav

# re: Sending Email with System.Net.Mail

Tuesday, January 2, 2007 9:54 AM by ScottGu

Hi Rajesh,

I believe it only checks that the email address is in a valid format.  When you send an email using that API it simply sends it to your local SMTP server, which then later forwards it to the destination address.  As such, it can't know at the time the email is sent whether a user is on the remote domain.

Thanks,

Scott

# re: Sending Email with System.Net.Mail

Wednesday, January 3, 2007 1:29 AM by rajesh

Hi scott,

Thanks for reply, but please if you have any idea how i validate the email through host dns server list. I only know that this can be validated as there are lots of product in the market which do the same thing.

Please do help me.!

Thanks

Rajesh Yadav

# re: Sending Email with System.Net.Mail

Sunday, January 7, 2007 1:42 AM by Salma

thanks and excellent

# re: Sending Email with System.Net.Mail

Monday, January 8, 2007 6:06 AM by Ashwar

Hello,

My company is using lotus notes dominos server to send emails, and I am using ASP.Net 1.1 to build a website which needs to send emails as a part of its functionality. Please help.

Ashwar

# re: Sending Email with System.Net.Mail

Tuesday, January 9, 2007 5:09 AM by Saravana Kumar

Hi,

       At end I am getting an error "Failure Sending Mail".Check the InnerException error "{"Unable to read data from the transport connection: net_io_connectionclosed."}" .Actually I gave Host is "localhost"

# re: Sending Email with System.Net.Mail

Tuesday, January 9, 2007 11:22 AM by Eti

Scott

I also discovered that symantec anti virus was the problem. Again, I cannot rely on this because the clients' machines will most definitely have  Virus protection turned on.

Additionally I noticed I can no longer initialise a new System.Net.Mail.Mailmessage() without including the to and from addresses!

Do you have any idea why this is so?

I would rather not include them at the initialisation stage since I have a list of addresses to send to in a comma delimited string and would rather not "bodge" it.

Thanks

Eti

# re: Sending Email with System.Net.Mail

Thursday, January 11, 2007 1:20 AM by Irfan Khan

Hi Scott,

A few months ago I was able to send the mail with the below code. But from yesterday I am getting "System.Net.Mail.SmtpException:The operation has timed out" error. I cannot figure out wots the problem.

Can u help me out.

Thanks Irfan

Web Config Code

---------------

<system.net>

<mailSettings>

<smtp from="irfan.a.khan@capgemini.com">

<network host="BOMEX002.corp.capgemini.com" port="25" userName="irfkhan" password="expert!1234" defaultCredentials="true" />

</smtp>

</mailSettings>

</system.net>

Code for Sending Mail

-----------------------

MailMessage message = new MailMessage();

       message.From = new MailAddress("irfan.a.khan@capgemini.com");

       message.To.Add(new MailAddress("irfan.a.khan@capgemini.com"));

       message.Subject = "This is a test mail";

       message.Body = "This is the content";

       SmtpClient client = new SmtpClient();

       client.Send(message);

# re: Sending Email with System.Net.Mail

Thursday, January 11, 2007 9:19 AM by Jens

also having trouble :(

i'm also having trouble using:

SmtpMail.SmtpServer = "mail.server.dk";

SmtpMail.Send(Sender, Receiver, strSubject, strBody);

turns out that .NET 2 requires username and password for the smtp.

If i use the same code in .NET 1.1 it works without any problems.

Any ideas for sending via smtp-server without providing username/pwd ???

# re: Sending Email with System.Net.Mail

Friday, January 12, 2007 3:48 PM by Kishore

Hi Scott,

I'm using the new system.net.mail class methods to compose email using asp.net 2.0, but when I execute the code to send email, I don't get any errors, but it doesn't send the email either.  I'm specifying the smptclient host, username and password for the domain in the code.  any help will be appreciated.  Thanks.

# re: Sending Email with System.Net.Mail

Friday, January 12, 2007 7:38 PM by ScottGu

Hi Kishore,

Usually when no errors happen, but no email gets sent, it means that the mail was sent to the local mail server, but it wasn't configured to forward it correctly.

Can you check your SMTP service to see if that might be the case.

Thanks,

Scott

# re: Sending Email with System.Net.Mail

Monday, January 22, 2007 1:04 PM by Jeremiah

Is there a way to force a delay when sending messages with System.Net.Mail?  For example, can I add a message to a queue and have it sent x hours/days later?

Thanks.

# re: Sending Email with System.Net.Mail

Wednesday, January 31, 2007 4:23 PM by SteevR

Hi Scott,

We have an exchange server that is separate from the production web server. I have an account set up for sending email on the exchange server. Internal mail works fine, but external mail does not work. Could you point me in some direction?

Thanks,

Steve

# re: Sending Email with System.Net.Mail

Wednesday, January 31, 2007 10:10 PM by Dummy

Shiver my (me) timbers...

Sending email asynchronously is not working.

1. Page directive is correct: (<%@ Page Async="true" %>)

2. Callback method runs but "e.Error.Message.ToString()" reports: "Failure sending mail."

3. Hence, email doesn't arrive. :<(

4. I guess I am stuck using the synchronous method because it works!

Snippet:

// SmtpClient

SmtpClient smtp = new SmtpClient();

smtp.EnableSsl = true; // Gmail requirement

if (smtp != null)

{

 // Asynchronously

 object userState = mail;

 smtp.SendCompleted += new SendCompletedEventHandler(SmtpClient_OnCompleted);

 smtp.SendAsync(mail, userState);

 // Synchronously

 smtp.Send(mail);

 Alert.Show(Global.FormsCompleteMsg, "Home.aspx");

}

# re: Sending Email with System.Net.Mail

Friday, February 2, 2007 7:44 AM by Lee Fear

I am still having the same problem with hotmail not receiving my emails from SmtpClient.Send(). I am using the following code which someone says works for them(although they use a pop server instead of localhost). All other addresses I send to (including Yahoo) receive the mails.

System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("localhost");

     System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage("someone@somewhere.com", "someone@hotmail.com", "Test Mail Subject", "Test Mail Body");

     client.Send(msg);

Would it be possible for someone to test this code and see if they can get it to send to hotmail? I would be very grateful as this is causing massive problems.

# re: Sending Email with System.Net.Mail

Friday, February 2, 2007 1:51 PM by Lee Fear

Thanks for all your help, but I have finally found the problem. My sentfrom address was name@blueyonder.co.uk and my server was completely different ie www.website.com

If I change the sentfrom address to postmaster@website.com it gets to hotmail. Hotmail must have extra security matching the host to the sender.

# re: Sending Email with System.Net.Mail

Tuesday, February 6, 2007 3:05 AM by tony

hai all, i am trying to make a "contact me" page based on the tutorial 8 of ASP.NET

the coding to send email is

Private Sub SendMail(ByVal from As String, ByVal body As String)

       Dim mailServerName As String = "SMTP.yahoo.com"

       Dim message As MailMessage = New MailMessage(from, "tony@yahoo.com", "feedback", body)

       Dim mailClient As SmtpClient = New SmtpClient

       mailClient.Host = mailServerName

       mailClient.Send(message)

       message.Dispose()

   End Sub

this is the error message i get.

An existing connection was forcibly closed by the remote host

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host

Source Error:

Line 15:

Line 16:         mailClient.Host = mailServerName

Line 17:         mailClient.Send(message)

Line 18:         message.Dispose()

Line 19:     End Sub

do i need to configure my SMTP

by default servername= 127.0.0.1 and port=25

thanks

# re: Sending Email with System.Net.Mail

Thursday, February 8, 2007 12:51 PM by tony

i solve the problem d

it is the mail server name

thanks

# re: Sending Email with System.Net.Mail

Monday, February 12, 2007 3:41 AM by anonymous post

We are using Chilkats Email DLL to be more flexible however many of our send emails get rejected because when sending the email via SMTP a RECEIVED HEADER is loged in the email header. The receiving email server (hotmail, yahoo) than tells us "No relay permitted"

That is because the email server and the webserver do not share the same IP address.

Does this also happens with ASP.NET.Mail?

# re: Sending Email with System.Net.Mail

Monday, February 12, 2007 2:13 PM by tony

hai i have a problem again.

i can run my program on my friend computer

but on my computer it shows this error message

Unable to read data from the transport connection: net_io_connectionclosed.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.

pls help me

thanks

i have tried to search the answer and configure the SMTP however it didnt work

# re: Sending Email with System.Net.Mail

Tuesday, February 20, 2007 3:54 AM by RobGMiller

Found the problem thanks to a previous message in this blog which gave me a clue.

The mail was going to the junk box which I checked but did not observe that it was not sorted by receive date.

As an asside: I did notice that the HTML was being converted to text. Does anyone know if this can be avoided in Outlook 2003.

# Did you find a sollution for avoiding Norton Antivirus

Friday, February 23, 2007 3:38 PM by Nistrea Florin

Please send me an e-mail if you found a solution...i'll probably won't be able to find this site again since i've found it with google!

uzzy_net@yahoo.com

Best Regards!

# The specified string is not in the form required for an e-mail address

Saturday, March 3, 2007 11:06 AM by Philip Lippard

I switched from System.Web.Mail to System.Net.Mail, however I am now reconsidering that move because if I send an email to an email address in the form john.doe@yahoo.com, I receive an error message "The specified string is not in the form required for an e-mail address".  I have conducted further testing and evidently the SmtpClient class Send method does not like the period "." between the "john" and "doe".   If I conduct a test with an email address in the form jdoe@yahoo.com...everything works fine.

This is a showstopper for me... if I am using System.Net.Mail to inform e-commerce customers of post-purchase activity. I can never predict when I may encounter a non-conforming email address.

Philip

# re: Sending Email with System.Net.Mail to a public folder

Thursday, March 8, 2007 3:01 PM by Cindy V

Is it possible to send an email using System.Net.Mail to a public folder in Exchange? I tried to do this using code that works when sending to a regular smtp address but it was returned as undeliverable. The error message was "The message reached the recipient's e-mail system, but delivery was refused." I don't know if this is a permission problem or how to accomplish this.

# re: Sending Email with System.Net.Mail

Tuesday, March 13, 2007 12:32 AM by Joshua

Hi Scott & All,

Just want to find out if there's any difference in sending out mails using either the (SMTPDeliveryMethod) Network Method or Pickup? We're leveraging on the W2K3 SMTP services to do so and also an email aliase to track the response of the email (including bounce mail). Another issue we realised is that when mails received in MS Outlook it will have its display name on the From field appended with an email alias address with the wordings of "on behalf of the senders actual email address" (eg., marketing_3_2061@domainname.com on behalf of Marketing [Marketing@domain.com]). However as compared to retrieving it in webmails (like Yahoo), there are no such issues, it will display the sender's email address. Any idea how this can be resolved?

# HTML Message to be loaded from a file

Tuesday, March 13, 2007 1:37 PM by Debi

I'm trying to send an html message, but the message ends up having no formatting, it just shows the source code. Has anyone had success with this?

msg = New System.Net.Mail.MailMessage()

msg.Subject = sSubject

sAddr = LoadSettings.Item("to")

aAddrs = Split(sAddr, ";")

For Each sAddr In aAddrs

   msg.To.Add(New MailAddress(Trim(sAddr)))

Next

msg.IsBodyHtml = True

oRead = System.IO.File.OpenText(ApplicationPath & sFileName)

EntireFile = oRead.ReadToEnd()

msg.Body = EntireFile

client.Send(msg)

# re: HTML Message to be loaded from a file

Tuesday, March 13, 2007 2:03 PM by Debi

sorry, that was due to a mistake on my part. now it displays html content. but i have another problem. this is a report that is exported to html from crystal report. Did not have any problems with outlook 2003, but due to new formatting issues with outlook 2007 it gets disfigured in 2007. the formatting is a problem when i export from crystal to html. so now i am planning to export as doc or pdf, and send that in the message. does anyone know if its possible to attach a  doc or pdf inline?

# re: Sending Email with System.Net.Mail

Sunday, March 18, 2007 3:20 PM by reef83

Hi, I need to send an activation email to every registered user.

the email should include a link that will direct user to activation address.

and the user id should be inside the link so that the activation page can get the user id and activate the user..

thx for any help... :)