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 12:56 AM by mike
For an example of how to embed images, have a look here:

http://mikepope.com/blog/DisplayBlog.aspx?permalink=1264

# 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 2:06 AM by Simone Busoli
For those who are still working with ASP.NET 1.1, DotNetOpenMail (http://dotnetopenmail.sourceforge.net/) is a great library. It allows inline graphics as well as SMTP authentication (http://dotnetopenmail.sourceforge.net/examples.html)

# re: Sending Email with System.Net.Mail

Sunday, December 11, 2005 3:41 AM by jayson knight
Excellent sample...the new mail namespace kicks the crap out of the old web.mail, which was such a crappy wrapper around CDONTS.

# 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 Majid Shahabfar
You can also check the following link:
http://www.systemwebmail.com
prepared by Dave Wanta which starts with an Introduction and Programming Samples. It concludes with resolutions to challenging errors and other resources.

# 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 21, 2005 11:39 AM by scottgu
Hi Eber,

Yes -- you can now encrypt any section value in a web.config file. This MSDN article goes into more details on how to-do this: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag2/html/paght000005.asp

Hope this helps,

Scott

# 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

Monday, January 02, 2006 5:43 PM by scottgu
There is a new web-site: http://www.systemnetmail.com/ which is dedicated to System.Net.Mail and I think has help with a few of these questions.

Hope this helps,

Scott

# re: Sending Email with System.Net.Mail

Wednesday, January 04, 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.

# <br> <br> <br> Geoff’s Blog :: Site error reporting <br> <br>

Saturday, February 25, 2006 3:14 PM by TrackBack



Geoff&#146;s Blog :: Site error reporting

# 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 01, 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 06, 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 06, 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 07, 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 08, 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

# Sending Money to India &raquo; Sending Email with AJAX: Building a Small Application

PingBack from http://sending-money-to-india.maxi02.info/sending-email-with-ajax-building-a-small-application/

# 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 05, 2006 3:15 PM by Prem
You guys are awesome!

# I can't get it work on my local machine

Thursday, August 10, 2006 5:06 AM by Kemal Emin
the code above (and many other variations) do not seem to send mail on my local machine. It gives no error messages but mail does not arrive to different mail addresses I tried. I also tried 127.0.0.1 instead of localhost, removed authentication parts of the string. and I tried many other things but no luck.. Any idea what could it be ?

# 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 5:06 PM by Derik
Hi Scott, thanks for the help with this great thread. Typically I'd handle my mail needs through a stored procedure xp_sendmail but, I would be much easier to use what is already cooked up in this new namespace. I've altered my web.config and my CS file as suggested but, I keep getting an error when I try to send mail: System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed. at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine) I'm trying to send mail from my ASP.Net app server to my local exchange server. I do not have SMTP insalled on the ASP.NET server - that shouldn't be a problem should it since I'm actually sending the mail through a different box? Any suggestions? I'd really like to leverage this over xp_sendmail if possible. Thanks! -D

# 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

Monday, September 04, 2006 5:48 AM by sreedhar
I seem to have a unique problem. The email seems to be going through without any problem, but the mail doesn't have the subject line I set or the body that I set. Could anyone please throw light on this situation? Here is my code: Dim objSMTPClient As New System.Net.Mail.SmtpClient() Dim objEmail As New System.Net.Mail.MailMessage() objEmail.To.Add(New System.Net.Mail.MailAddress("abc@xyz.com")) objEmail.Subject = "Error in page '" + cVariables.strErrorUrl.ToString + "'" objEmail.Body = "Body" objEmail.IsBodyHtml = True objSMTPClient.Send(objEmail)

# re: Sending Email with System.Net.Mail

Friday, September 08, 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

Thursday, September 28, 2006 10:37 PM by Nisar Khan
Scott question for you i'm generating my body of my text from .htm file which is located in the folder of my project like typical .htm file with colors and fonts and stuffs and my email.htm file has its own css class like styling and when i send email i do not get any coloring or fonts? if i remove my css reference and hardcode everything in the .htm like font color and fonts and then send email, i get email with colors and font types..... i'm using outlook client for my email any suggustions? Thanks Nisar

# 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 02, 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 02, 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 <%@ Page Language="C#" Async="true"%>. 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."

# Culpepper Web Design Developer Blog &raquo; Blog Archive &raquo; MailMessage &#8220;To&#8221; Multiple Email Addresses

PingBack from http://blog.culpepperwebdesign.com/?p=11

# re: Sending Email with System.Net.Mail

Monday, October 16, 2006 4:57 AM by Param
Hi Scott, I am using This code to send email,in VS2005,Can u please suggest what should i fill in Smtp Server As I am using it on same machine and what should i do if i want to check it from my yahoo Id,Actually I am Making contact us page ,in which mail is sent to administrator when user clicks button

# re: Sending Email with System.Net.Mail

Tuesday, October 17, 2006 6:30 AM by Lee Fear
I am attempting to send mail from a test site on my home computer (windows xp pro). I have SMTP set up and the firewall has port 25 open. If I run the following code on a .net1.1 site it works. ------------------------------------------------------------------------------------------------- MailMessage mail=new MailMessage(); mail.To=sendtoemail; mail.From=fromemail; mail.Body=strBody; mail.Subject="Registration Confirmation"; SmtpMail.SmtpServer="127.0.0.1"; try { SmtpMail.Send(mail); } catch(Exception ex) { string errex=ex.Message; } -------------------------------------------------------------------------------------------------- But if I run the same code on a 2.0 site is does not work, I get no errors but the mail never arrives at my inbox. Also if I use the Suggested SMTPClient code below, it also does not work. I get no errors but the mail never arrives at my inbox. --------------------------------------------------------------------------------------------------- MailMessage mail = new MailMessage(); mail.To.Add(sendtoemail); MailAddress address = new MailAddress(fromemail); mail.From = address; mail.Body = "This is a test Mail"; mail.Subject = "test mail"; try { SmtpClient snd = new SmtpClient(); snd.Host = "127.0.0.1"; snd.Send(mail); } catch (Exception ex) { string errex = ex.Message; } --------------------------------------------------------------------------------------------------- Any ideas on why the 1.1 version works but the 2.0 does not?

# 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 12:04 AM by kee
I keep having the error "Failure sending mail." when sending mail to localhost. I'd tried turning off all the firewalls running on my machine. Any suggestions?

# 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 02, 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 04, 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 07, 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 07, 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

# Are these bug reports accurate?

Monday, November 20, 2006 11:38 AM by Rob

Scott, great article (and site / blog in general), but before I started using this namespace, I just wanted to check if the issues raised in this article were much of a problem.

http://www.developer.com/net/asp/article.php/3639096

There's two - one relating to capitalisation of headers, which worries me just 'cause I don't want my mail being junked when I could use another method to avoid this, and another regarding the priority of messages, which doesn't concern me so much.

Is this stuff still relevant?

Cheers

Rob

# 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 2:56 PM by Shawn

Hello,

I am having an issue with sesnding to multiple recipients.  I have tried every suggestion on this thread but my application still will only send the email to the first person in the list of recipients.

I have tried setting the ToAddress value to a comma delimited list of emails.  

mail.to.add(new message("xxx@xx.com, yyy@xx.com"))

I have tried adding each email address separately:

mail.to.add(new message("xxx@xx.com"))

mail.to.add(new message("yyy@xx.com"))

I even tried what Curt recommended by putting the first recipient in the line that instantiates the message object and then adding the other recipient afterwards using the example code above.  Nothing works.  It always only sends to the first recipient.

Help?

# 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 04, 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 05, 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 06, 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