Answered by:
How do I send mail using C#?

Question
-
Does anyone have a code snippet that shows how to send mail from c#?Wednesday, April 6, 2005 11:21 PMModerator
Answers
-
Here is the code snippet I found...
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("luckyperson@online.microsoft.com");
message.Subject = "This is the Subject line";
message.From = new System.Net.Mail.MailAddress("From@online.microsoft.com");
message.Body = "This is the message body";
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("yoursmtphost");
smtp.Send(message);Wednesday, April 6, 2005 11:22 PMModerator -
Dear Josh,
Thank you very much for the great post. It really demonstrates everything easily. Hope that you wouldn't mind some minor notes about it anyway:
1-The namespace System.Net.Mail is a part of the class library of .NET framwork 2.0 (currently in BETA version), to send mail using .NET framework 1.1, you'd use System.Web.Mail instead..
2-There's no class called SmtpClient in the System.Web.Mail namspace, but it's a member of the System.Net.Mail namspace in .NET Framework 2.0.
To send mail via Microsoft .NET Framework 1.1 (the current version) you can use:System.Web.Mail.MailMessage message=
new System.Web.Mail.MailMessage();
message.From="from e-mail";
message.To="to e-mail";
message.Subject="Message Subject";
message.Body="Message Body";
System.Web.Mail.SmtpMail.SmtpServer="SMTP Server Address";
System.Web.Mail.SmtpMail.Send(message);
System.Web.Mail.SmtpMail.SmtpServer="SMTP Host Address";
System.Web.Mail.SmtpMail.Send("from","To","Subject","MessageText");
Now, in fact, both segments of code will not work for most SMTP hosts. This is because most SMTP hosts today require authentication (user/pass) to allow you to use the server. To send mail using Authenticated SMTP, many people use third party tools. There are many out there and some of them are good and free, but, System.Web.Mail doesn't need that really. You can send mail via Authenticated SMTP mail servers using the 1st code I wrote, just add the bold lines to it to be:System.Web.Mail.MailMessage message=
new System.Web.Mail.MailMessage();message.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",1 );
message.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/sendusername","SmtpHostUserName" );
message.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/sendpassword","SmtpHostPassword" );
message.From="from e-mail";
message.To="to e-mail";
message.Subject="Message Subject";
message.Body="Message Body";System.Web.Mail.SmtpMail.SmtpServer="SMTP Server Address";
System.Web.Mail.SmtpMail.Send(message);
For more detailed information on sending mail using .NET framework 1.1, check this detailed FAQ (take care, it's often detailed more than you may need!).
For information on the System.Net.Mail namespace in Microsoft.NET Framework 2.0, you may check Visual Studio 2005 Library > .NET Framework Reference > Class Library > System.Net.Mail.
Wish to hear if this could help
Regards,Friday, April 8, 2005 2:15 AM -
spamming is not good at all and such discussions would not be allowed at all. but to send bulkemails totally depends on the network speed and how fast your system is - nothing else.
Need 2 be back @ MS - MS All the way! Follower since 1995 MS Super Evangelist| MSDN Forums Moderator- Marked as answer by ahmedilyasModerator Tuesday, March 3, 2009 7:18 PM
Tuesday, March 3, 2009 7:18 PMModerator
All replies
-
Here is the code snippet I found...
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("luckyperson@online.microsoft.com");
message.Subject = "This is the Subject line";
message.From = new System.Net.Mail.MailAddress("From@online.microsoft.com");
message.Body = "This is the message body";
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("yoursmtphost");
smtp.Send(message);Wednesday, April 6, 2005 11:22 PMModerator -
Dear Josh,
Thank you very much for the great post. It really demonstrates everything easily. Hope that you wouldn't mind some minor notes about it anyway:
1-The namespace System.Net.Mail is a part of the class library of .NET framwork 2.0 (currently in BETA version), to send mail using .NET framework 1.1, you'd use System.Web.Mail instead..
2-There's no class called SmtpClient in the System.Web.Mail namspace, but it's a member of the System.Net.Mail namspace in .NET Framework 2.0.
To send mail via Microsoft .NET Framework 1.1 (the current version) you can use:System.Web.Mail.MailMessage message=
new System.Web.Mail.MailMessage();
message.From="from e-mail";
message.To="to e-mail";
message.Subject="Message Subject";
message.Body="Message Body";
System.Web.Mail.SmtpMail.SmtpServer="SMTP Server Address";
System.Web.Mail.SmtpMail.Send(message);
System.Web.Mail.SmtpMail.SmtpServer="SMTP Host Address";
System.Web.Mail.SmtpMail.Send("from","To","Subject","MessageText");
Now, in fact, both segments of code will not work for most SMTP hosts. This is because most SMTP hosts today require authentication (user/pass) to allow you to use the server. To send mail using Authenticated SMTP, many people use third party tools. There are many out there and some of them are good and free, but, System.Web.Mail doesn't need that really. You can send mail via Authenticated SMTP mail servers using the 1st code I wrote, just add the bold lines to it to be:System.Web.Mail.MailMessage message=
new System.Web.Mail.MailMessage();message.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",1 );
message.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/sendusername","SmtpHostUserName" );
message.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/sendpassword","SmtpHostPassword" );
message.From="from e-mail";
message.To="to e-mail";
message.Subject="Message Subject";
message.Body="Message Body";System.Web.Mail.SmtpMail.SmtpServer="SMTP Server Address";
System.Web.Mail.SmtpMail.Send(message);
For more detailed information on sending mail using .NET framework 1.1, check this detailed FAQ (take care, it's often detailed more than you may need!).
For information on the System.Net.Mail namespace in Microsoft.NET Framework 2.0, you may check Visual Studio 2005 Library > .NET Framework Reference > Class Library > System.Net.Mail.
Wish to hear if this could help
Regards,Friday, April 8, 2005 2:15 AM -
You can always send e-mail using the end-users Microsoft Office Outlook interface. To do so, the needed library is provided below:
http://www.xblogs.org/Downloads/AppLibraries/OutlookMail.zipFriday, April 8, 2005 3:25 AM -
Recently I used FreeSmtp.NET successfully. It allows to send text- and HTML-messages with inline images and of course with attachments.
It even allows to send text and HTML inside one message (multiple mime-parts).Friday, April 8, 2005 4:41 AM -
Not that everyone cares, just that maybe one or two do. Here's how to post an email to an Exchange Server mailbox over http using WebDAV.
public static void SendEmail(string server, string mailbox, string password, string to, string subject, string body, bool secureHttp)
{
string httpProtocol = secureHttp ? "https://" : "http://";
string mailboxUri = httpProtocol + server + "/" + mailbox;
string submissionUri = httpProtocol + server + "/" + mailbox + "/##DavMailSubmissionURI##/";
string draftsUri = "http://" + server + "/" + mailbox + "/drafts/" + subject + ".eml";string message = "To: " + to + "\n" +
"Subject: " + subject + "\n" +
"Date: " + System.DateTime.Now +
"X-Mailer: mailer" + "\n" +
"MIME-Version: 1.0" + "\n" +
"Content-Type: text/plain;" + "\n" +
"Charset = \"iso-8859-1\"" + "\n" +
"Content-Transfer-Encoding: 7bit" + "\n" +
"\n" + body;// Credentials for exchange requests.
CredentialCache credentials = new CredentialCache();
credentials.Add(new Uri(mailboxUri), "NTLM", new NetworkCredential(mailbox, password));// Request to put an email the drafts folder.
HttpWebRequest putRequest = (HttpWebRequest)HttpWebRequest.Create(draftsUri);
putRequest.Credentials = credentials;
putRequest.Method = "PUT";
putRequest.ContentType = "message/rfc822";byte[] bytes = Encoding.UTF8.GetBytes((string)message);
putRequest.ContentLength = bytes.Length;Stream putRequestStream = putRequest.GetRequestStream();
putRequestStream.Write(bytes, 0, bytes.Length);
putRequestStream.Close();// Put the message in the Drafts folder of the sender's mailbox.
WebResponse putResponse = (HttpWebResponse)putRequest.GetResponse();
putResponse.Close();// Request to move the email from the drafts to the mail submission Uri.
HttpWebRequest moveRequest = (HttpWebRequest)HttpWebRequest.Create(draftsUri);
moveRequest.Credentials = credentials;
moveRequest.Method = "MOVE";
moveRequest.Headers.Add("Destination", submissionUri);// Put the message in the mail submission folder.
WebResponse moveResponse = (HttpWebResponse)moveRequest.GetResponse();
moveResponse.Close();
}Friday, April 8, 2005 5:59 AM -
Similar to Josh: I need to know how to send mail using C#. I have a class that will be throwing parameters (see below):
private
void SendToAnalyst(){
string emailSubject = string.Empty; string emailAddress = string.Empty;StringBuilder sb =
new StringBuilder(); //To Do: Instantiate Monitoring Component if(mSourceSystem.ToUpper().Equals("FLEXCAB")){
emailSubject = "Sample RequestId (FLEXCAB To RADTI RESPONSE): "+mSampleRequestID;
sb.Append("**************************************************************************************\n");
sb.Append("\n");
sb.Append("Please do not reply to this email. This is a System generated email.\n");
sb.Append("\n");
sb.Append("**************************************************************************************\n");
sb.Append("\n");
sb.Append("Sample Request ID: "+mSampleRequestID+"\n");
sb.Append("Request Status: "+ mReqStatus+"\n");
sb.Append("\n");
sb.Append("Please Correct the error and re-submit.\n");
sb.Append("Or Call the EDS DBA on 03-8866-7424\n");
//Console.WriteLine(sb.ToString()); // Send the email body to Monitoring component}
}
The send mail class I am trying to create should catch the parameters from this SendToAnalyst class.
Monday, May 2, 2005 4:46 AM -
Is this for sending mail from a web page or from a Windows Forms application? Thanks!
Josh Ledgard wrote: Here is the code snippet I found...
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("luckyperson@online.microsoft.com");
message.Subject = "This is the Subject line";
message.From = new System.Net.Mail.MailAddress("From@online.microsoft.com");
message.Body = "This is the message body";
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("yoursmtphost");
smtp.Send(message);Thursday, September 1, 2005 5:55 PM -
The system.net.mail class is the recomended way to handle mail sends no matter what sort of application you are building.
Thursday, September 1, 2005 7:04 PMModerator -
Thanks, Josh!
Friday, September 2, 2005 1:11 AM -
Hi josh
I use your code at the office it is working fine, but at home i get with te same code an error:
SmtpException was unhandled Failure sending mail.
I use a winXP Pro SP2 only the smtp server is different ?
can you help me
thanks
redspider- Proposed as answer by nikv75 Tuesday, January 26, 2010 9:50 PM
Monday, September 26, 2005 7:54 PM -
This was helful,
but the only problem that I face is authentication, so please provide an explicit example.
Let us say for instance that my e-mail (from field) is: "from@yahoo.com" with user name: "from" and password: "password", and I am sending to: "to@hotmail.com".
That is what I am trying to do for months...
Thanks a lotFriday, October 14, 2005 7:04 AM -
I forget to ask how to get the SMTP name of my mail server?
Is it like: mail.yahoo.com, hotmail.com, gmail.com ? or what?
Thanks againFriday, October 14, 2005 7:11 AM -
Hi,
I have McAffee Scan On-Access disabled and problem is gone
greetzSaturday, November 12, 2005 10:50 PM -
Dear Mohamed,
I was very interested to try the code snippet using authentificated SMTP you gave us, but I cannot find and member Fields in the System.Web.Mail.MailMessage object.
How come I am the only one ? Did I do something wrong ?
Thanks,
Wednesday, January 11, 2006 5:03 PM -
hi i need to send e-mail through my C# application (VS .NET 2003)..i am using mohamed's code but getting the following exception
System.Web.HttpException: Could not access 'CDO.Message' object. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException (0x8004020E): The server rejected the sender address. The server response was: 530 5.7.0 Must issue a STARTTLS command first f17sm780958qba
could you guys help me in sorting this out...Thanks in advance
Tuesday, February 21, 2006 12:32 PM -
Hi all...I could rectify the above problem by adding this line
message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
I was using GMAIL smtp server which requires SSL.
Thanks
Friday, February 24, 2006 2:59 PM -
I had written another open source client one afternoon some time ago though it is rather useless with 2.0 (except for the email validation code) http://sourceforge.net/projects/no-cdo
Cheers,
Greg
Tuesday, February 28, 2006 9:13 PM -
public
void Send() {MailMessage MailMesaji = new MailMessage();
MailMesaji.Subject = "subject";
MailMesaji.Body = "mail body";
MailMesaji.BodyEncoding = Encoding.GetEncoding("Windows-1254"); // Turkish Character Encoding
MailMesaji.From =
"sender mail adress"; this.MailMesaji.To.Add(new MailAddress("to mail adress"));System.Net.Mail.SmtpClient Smtp = new SmtpClient();
Smtp.Host = "smtp.gmail.com"; // for example gmail smtp server
Smtp.EnableSsl =
true;Smtp.Credentials =
new System.Net.NetworkCredential("account name", "password");Smtp.Send(MailMesaji);
}
it is required that you have to enable smtp service from your mail settings.. (for gmail you also enable ssl option.)
is it enough ???
Friday, March 17, 2006 4:23 PM -
I'm just trying this code but it doesn't working
the error messege is "The remote server returned an error: (403) Forbidden.
i was trying to change the draft code
//string draftsUri = "http://" + server + "/" + mailbox + "/drafts/" + subject + ".eml";
to
string
draftsUri = httpProtocol + server + "/" + mailbox + "/drafts/" + subject + ".eml";to use the secure HTTP
it also returned this error "The function completed successfully, but must be called again to complete the context"
Any Help .....
Thursday, March 23, 2006 11:40 AM -
This code has really worked well for me, but I am having some issues in getting it to work over https as we are using a self published certificate. I am using the following code to supposedly trust all certificates, but I am still getting an 401 unauthorized error. I don't get this error when I use it over http, and I know that the exchange server is set up for https as that is how our Outlook Web is running.
public
class TrustAllCertificatePolicy : ICertificatePolicy{
public TrustAllCertificatePolicy(){ }
#region
ICertificatePolicy Members bool ICertificatePolicy.CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem){
return true;}
#endregion
}
I have heard that this is now obsolete in .NET 2.0. If this is the case, what should be used, and how should it be used.
Thursday, March 30, 2006 12:00 AM -
>is it enough ???
LOL
I hope it is, ...I will try in a few moment.
Bye
Saturday, April 8, 2006 6:18 PM -
Unfortunately, it does not work.
After 100 seconds an operation timeout exception is thrown (it is an smtpException).
Here is the code:
smtpClient.DeliveryMethod =
SmtpDeliveryMethod.Network;smtpClient.Timeout = _smtpTimeoutMilliseconds;
if (_smtpServer.Length == 0) throw new EmailNotifierException(this,n,"SMTP Server not specified");smtpClient.Host = _smtpServer;
smtpClient.Port = _smtpPort;
if (_username.Length > 0 && _userpassword.Length > 0)smtpClient.Credentials =
new System.Net.NetworkCredential(_username, _userpassword); if (_SSL)smtpClient.EnableSsl =
true; elsesmtpClient.EnableSsl =
false; MailMessage mail = new MailMessage();mail.From =
new MailAddress(_fromAddress,_fromName); foreach (MailAddress a in _toAddresses)mail.To.Add(a);
foreach (MailAddress a in _ccAddresses)mail.CC.Add(a);
foreach (MailAddress a in _bccAddresses)mail.Bcc.Add(a);
mail.IsBodyHtml =
false;mail.Priority = (
MailPriority) _priority;mail.Subject = _subjectPrefix +
" " + _name + " notification.";mail.DeliveryNotificationOptions = (
DeliveryNotificationOptions)_deliveryNotification;mail.Body = createTextBody(n);
smtpClient.SendCompleted +=
new SendCompletedEventHandler(SendCompletedCallback); try{
if (_aSyinc)smtpClient.SendAsync(mail, n);
elsesmtpClient.Send(mail);
}
catch (SmtpException exc) { throw new EmailNotifierException(this, n, exc.Message); } catch (Exception exc) { throw new EmailNotifierException(this, n, exc.Message); }Saturday, April 8, 2006 8:15 PM -
i'm succeeded to connect to Exchange server as SMTP
not need this code just use the simple smtp code and go on
Monday, April 10, 2006 8:50 AM -
//For VS2003 Add the COM “Microsoft CDO for Windows 2000 Library” reference
public
void CDOSendCC(string from, string Recipients, string RecipientsCC, string url, string Subject, string user, string password){
try{
CDO.MessageClass Message =
new CDO.MessageClass();CDO.ConfigurationClass iConf =
new CDO.ConfigurationClass();iConf.Fields[CDO.CdoConfiguration.cdoSendUsingMethod].Value = CDO.CdoSendUsing.cdoSendUsingPort;
iConf.Fields[CDO.CdoConfiguration.cdoSMTPServer].Value =
"smtpServer";iConf.Fields[CDO.CdoConfiguration.cdoSMTPAuthenticate].Value = CDO.CdoProtocolsAuthentication.cdoBasic;
iConf.Fields[CDO.CdoConfiguration.cdoSendUserName].Value = user;
iConf.Fields[CDO.CdoConfiguration.cdoSendPassword].Value = password;
iConf.Fields.Update();
Message.Configuration = iConf;
Message.From = from;
Message.To = Recipients;
Message.CC = RecipientsCC;
Message.Subject = Subject;
Message.CreateMHTMLBody(url, CDO.CdoMHTMLFlags.cdoSuppressAll,
"", "");Message.Send();
}
catch (System.Web.HttpException ehttp){
Console.Write(ehttp.Message); Console.Write(ehttp.InnerException.Message);}
catch (System.Exception ex){
Console.Write(ex.Message);}
}
//VS2005 Use the follow
private
void SendMail(){
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("somemail@domain.com");
message.CC.Add("someothermail@domain.com");
message.Subject = "This is the Subject line";
message.From = new System.Net.Mail.MailAddress("frommail@domain.com");
System.IO.TextReader txtRead = new System.IO.StreamReader(@"D:\Attachments\Directory\CM-ODM Directory\13 06\checksum.txt");
message.Body = txtRead.ReadToEnd();
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtpServer",25);
smtp.Credentials = new NetworkCredential("username", "password");
smtp.Send(message);
}
Monday, April 10, 2006 9:47 PM -
Of course I am not the alone one who sent you a similar code, but I wish to emphasize how to enter the parameter SmtpMail.SmtpServer in case of a mail from a server. The value "localhost" is a place holder for the address of the mail server. You can use it as well, i.e. you do not need to know the really address of the mail server.
public void SendMail(string subject, string body)
{
MailMessage MyMail = new MailMessage();
SmtpMail.SmtpServer = "localhost"; // from server
// or
SmtpMail.SmtpServer = "mailto.t-online.de"; // example from local PCMyMail.From = "mail address";
MyMail.To = "mail address";
MyMail.Subject = subject;
MyMail.Body = body;
SmtpMail.Send(MyMail);
}Have a fun!
Valentin
Do not hesitate to contact me!
Friday, April 21, 2006 12:12 AM -
I have a similar requirement where I need to send mail via exchange server. Can yo tell me how did you connect to exchange server as SMTP?
Thanks in advance!
Anand.
Friday, May 26, 2006 1:53 PM -
The PUT / MOVE method of sending mail via WebDAV works well for IIS/6.0 servers, but in my experience the MOVE fails with IIS/5.0 servers. Has anyone seen this, or have an idea what's going on?
MarcFriday, June 2, 2006 5:13 AM -
what is the error message ChatterEmail??, webdav is installed in IIS 5.0 by default, so maybe you are having security error, I was having some "no relay" problems using programmatically authentication so if it is you case try using the App.config to declare the Credentials, I don’t know why putting credentials in App.Config works better than using programmatically, but it appends to me. Here is an example:
<system.net>
<mailSettings>
<smtp from="yoursenderemail@corporate.com">
<network host="hostname" password="Password" userName="exchangeuserID" />
</smtp>
</mailSettings>
</system.net>
*Note that the username is the user you use to log in through Outlook, not your Alias to send email.
Friday, June 2, 2006 1:25 PM -
The strange thing is that there is no error; my app just never gets a reply to the MOVE (I get a 100 Continue and then a 201 Created for the PUT). Is it possible that IIS/5.0 is closing the connection after a PUT and I need to re-open it? My code works perfectly on all IIS/6.0 systems as is (i.e. I assume the HTTP connection remains open).
MarcFriday, June 2, 2006 4:59 PM -
ChatterEmail, it will be very dificult to figure out whats hapening with out doing some research first, enable logging for IIS, if there is no error message, try to reproduce the error on an isolated environtment, try to send the email using CDONTS to see if it work, check if you have access to the inbox, attachments etc.;...... Im using this function to search for unread items, download all their attachments and then mark them as read to not to catch them again... hope this can help you.
//VS2005, slightly modified microsoft code
public static void BrowseInbox(string path, string server, string user,string userid,string password)
{
// Variables.
System.Net.HttpWebRequest Request;
System.Net.WebResponse Response;
string strRootURI = "http://" + server + "/Exchange/" + user + "/inbox/";
string strUserName = userid;
string strPassword = password;
string strDomain = "domain";
string strQuery = "";
byte[] bytes = null;
System.IO.Stream RequestStream = null;
System.IO.Stream ResponseStream = null;
XmlDocument ResponseXmlDoc = null;
XmlNodeList DisplayNameNodes = null;
strQuery = "<?xml version=\"1.0\"?><D:searchrequest xmlns:D = \"DAV:\" >"
+ "<D:sql>select "
+ "\"urn:schemas:httpmail:fromemail\""
+ ", \"urn:schemas:httpmail:read\""
+ " from scope ('shallow traversal of "
+ (char)(34) + strRootURI + (char)(34) + "') WHERE \"urn:schemas:httpmail:read\" = false AND \"urn:schemas:httpmail:hasattachment\" = true "
+ " </D:sql></D:searchrequest>";
System.Net.CredentialCache MyCredentialCache;
MyCredentialCache = new System.Net.CredentialCache();
MyCredentialCache.Add(new System.Uri(strRootURI), "NTLM", new NetworkCredential(strUserName,strPassword,strDomain));
Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(strRootURI);
Request.Credentials = MyCredentialCache;
Request.Method = "SEARCH";
bytes = Encoding.UTF8.GetBytes((string)strQuery);
Request.ContentLength = bytes.Length;
Request.Timeout = 600000;
RequestStream = Request.GetRequestStream();
RequestStream.Write(bytes, 0, bytes.Length);
RequestStream.Close();
Request.ContentType = "text/xml";
Response = (HttpWebResponse)Request.GetResponse();
ResponseStream = Response.GetResponseStream();
ResponseXmlDoc = new XmlDocument();
ResponseXmlDoc.Load(ResponseStream);
DisplayNameNodes = ResponseXmlDoc.GetElementsByTagName("a:response");
if (DisplayNameNodes.Count > 0)
{
Console.WriteLine("Non-folder item display names...");
for (int i = 0; i < DisplayNameNodes.Count; i++)
{
SetRead(DisplayNameNodes
["a:href"].InnerXml, new NetworkCredential(strUserName, strPassword,strDomain));
ReadAttach(DisplayNameNodes
["a:href"].InnerXml, path, DisplayNameNodes
["a:propstat"].GetElementsByTagName("a:prop")[0]["d:fromemail"].InnerText, new NetworkCredential(strUserName, strPassword, strDomain));
}
}
else
{
Console.WriteLine("No non-folder items found...");
}
ResponseStream.Close();
Response.Close();
}
Friday, June 2, 2006 10:35 PM -
Hi,
I was attempting to do the same thing earlier, using similar code. I also tried code suggested in Microsoft's help files for this purpose. However, when I attempt to send e-mail it claims that the host is refusing it. The Microsoft code that I tried is as follows:
using System; using System.Web.Mail; namespace SendMail { class usage { public void DisplayUsage() { Console.WriteLine("Usage SendMail.exe <to> <from> <subject> <body>"); Console.WriteLine("<to> the addresses of the email recipients"); Console.WriteLine("<from> your email address"); Console.WriteLine("<subject> subject of your email"); Console.WriteLine("<body> the text of the email"); Console.WriteLine("Example:"); Console.WriteLine("SendMail.exe SomeOne@Contoso.com;SomeOther@Contoso.com Me@contoso.com Hi hello"); } } class Start { // The main entry point for the application. [STAThread] static void Main(string[] args) { try { try { MailMessage Message = new MailMessage(); Message.To = args[0]; Message.From = args[1]; Message.Subject = args[2]; Message.Body = args[3]; try { SmtpMail.SmtpServer = "your mail server name goes here"; SmtpMail.Send(Message); } catch(System.Web.HttpException ehttp) { Console.WriteLine("{0}", ehttp.Message); Console.WriteLine("Here is the full error message output"); Console.Write("{0}", ehttp.ToString()); } } catch(IndexOutOfRangeException) { usage use = new usage(); use.DisplayUsage(); } } catch(System.Exception e) { Console.WriteLine("Unknown Exception occurred {0}", e.Message); Console.WriteLine("Here is the Full Message output"); Console.WriteLine("{0}", e.ToString()); } } } }
(Obviously I inserted the appropriate mail server). Here is the exact error message the program gives me when I run it:
Exception occurred Failure sending mail.
Here is the full message output:
System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebExceptio
n: Unable to connect to the remote server ---> System.Net.Sockets.SocketExceptio
n: An established connection was aborted by the software in your host machine
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddre
ss socketAddress)
at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Sock
et s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state,
IAsyncResult asyncResult, Int32 timeout, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object ow
ner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket
6, Int32 timeout)
at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32
timeout, GeneralAsyncDelegate asyncCallback)
at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate
asyncCallback)
at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncD
elegate asyncCallback, Int32 creationTimeout)
at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
--- End of inner exception stack trace ---
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at SendMail.Start.Main(String[] args) in C:\Ethan\Experimental\MailMessage\Ma
ilMessage\Program.cs:line 82I'm not sure if anyone has spoken to this issue yet or not, but I can't figure out how to get this to work to save m=y life.
I have tried both this code directly and several modifications of it, including using System.Net.Mail (with appropriate modifications).
Can anyone help me? The server I am using is a standard Windows server. I am able to ping it successfully. I am told by my network administrator that the same server can be used both as an exchange server and as a SMTP server. In addition, authentication is NOT necessary.
Any ideas on what I am doing wrong? I am at my whit's end in terms of why this is not working.
Thanks,
Ethan S.Friday, July 21, 2006 1:44 PM -
EthanS, Try some of the many examples in this forum; if they didn’t work probably it is a configuration issue in your server, if it is refusing connection probably the firewall is blocking the default port #25, you can also try to use servername instead of the IP address.
Friday, July 21, 2006 2:30 PM -
Try this Out:
using System;
using System.Net.Mail;
class Mailer
{
enum MailMessagePart
{
From,
To,
Subject,
Message
}
static void Main(string[] args)
{
if (args.Length < 4)
{
Console.WriteLine(
"Expected: mailer.exe [from] [to] [subject] [message]");
return;
}
// Set mailServerName to be the name of the mail server
// you wish to use to deliver this message
string mailServerName = "smtphost";
string from = args[(int) MailMessagePart.From];
string to = args[(int) MailMessagePart.To];
string subject = args[(int) MailMessagePart.Subject];
string body = args[(int) MailMessagePart.Message];
try
{
// MailMessage is used to represent the e-mail being sent
using (MailMessage message =
new MailMessage(from, to, subject, body))
{
// SmtpClient is used to send the e-mail
SmtpClient mailClient = new SmtpClient(mailServerName);
// UseDefaultCredentials tells the mail client to use the
// Windows credentials of the account (i.e. user account)
// being used to run the application
mailClient.UseDefaultCredentials = true;
// Send delivers the message to the mail server
mailClient.Send(message);
}
Console.WriteLine("Message sent.");
}
catch (FormatException ex)
{
Console.WriteLine(ex.Message);
}
catch (SmtpException ex)
{
Console.WriteLine(ex.Message);
}
}
}Friday, July 28, 2006 5:59 PM -
Hi,
I figured out what was wrong with my previous code. It was actually my virus scan (McAffee). Has anyone encountered this problem before? Is there a good way around that? I don't want to have to disable my virus software every time that I need to run this code.
Thanks,
Ethan S.Friday, July 28, 2006 8:04 PM -
EthanS that's some weird, because Virus scan prevents to use port 25 in the server computer it is running, not at your local computer, probably it is blocking any new application trying to access internet, not only email, if this is the case, allow access to internet to your application using Virus scan console, If you don’t have rights to do it, it will restore default settings every time you change it, ask you administrator about that.Friday, July 28, 2006 8:41 PM
-
Hello,
the basic problem: SmtpException was unhandled by user code Failure sending mail. {working with asp net 2.0 and C#}
When i want to send an e mail i get the failure message you talked about. I ve been looking for solutions. i ve done these things below;
everything is in http://www.codeproject.com/aspnet/techblaster.asp i ve done and for summary;
Setting SMTP server
Before running the application you need to confirm these server settings:
- Make sure that the SMTP server is running, only then it can relay mail. If not, open the IIS window, in IIS look for the "local computer" on the left side tree view under which you will see the "Default SMTP Virtual Server", if it is not available, then you need to install it.
- To configure "Default SMTP Virtual Server", right-click on it, go into "Properties", and select "Access" tab, and then click the "Relay" button. With "only the list below" radio button selected, you should see the local IP address: "127.0.0.1", if it's not there, you need to add it.
- If you are using "localhost" or "127.0.0.1" as the
SmtpMail.SmtpServer
, make sure "Anonymous access is allowed". To allow access, open up the IIS. Locate the SMTP virtual server, and right-click select Properties. On the Access tab, click the Authentication button. Make sure "Anonymous Access" is the only checkbox checked. - Use real from and to addresses that exist on the
SmtpMail.SmtpServer
. Do not use invalid address
But still i cannot send my mail? So any solution?
Thanks a lot.
// These are my codes
using
System;using
System.Data;using
System.Configuration;using
System.Collections;using
System.Web;using
System.Web.Security;using
System.Web.UI;using
System.Web.UI.WebControls;using
System.Web.UI.WebControls.WebParts;using
System.Web.UI.HtmlControls;using
System.Net.Mail;public
partial class mail1 : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e){
}
protected void Button1_Click(object sender, EventArgs e){
MailMessage objMsg = new MailMessage(TextBox1.Text, TextBox2.Text); if (TextBox3.Text != ""){
objMsg.CC.Add(TextBox3.Text);
}
if (TextBox4.Text != ""){
objMsg.Bcc.Add(TextBox4.Text);
}
if (TextBox5.Text != ""){
objMsg.Subject = TextBox5.Text;
}
objMsg.Body = TextBox6.Text;
objMsg.IsBodyHtml =
true;objMsg.Priority =
MailPriority.High; if (TextBox7.Text != ""){
Attachment objAttc = new Attachment(TextBox7.Text);objMsg.Attachments.Add(objAttc);
}
SmtpClient objClient = new SmtpClient("localhost",25);objClient.Send(objMsg);
Label8.Text =
"Mail Gönderildi";}
}
Monday, August 7, 2006 4:23 PM -
I was having a similar problem with my code. My problem was with my virus scan program. Try disabling your virus scan temporarily and running the program; if it works while the virus scan program is disabled, that is the problem. Re-enable it and adjust your settings. I am using McAffee, so here's how you fix it in there:
1. Go to the virus scan console (you can get there by right-clicking on the virus scan symbol on the toolbar next to your clock and clicking on "VirusScan Console").
2. Double-click on "Access Protection"
3. Find the rule that says "Prevent mass mailing worms from sending mail" and edit it.
4. Add your program to the list of "Excluded Processes."
5. Click OK, apply the change, and close the console.
This may fix your problem. If not, it is something else, but this is the first thing I would look at. The problem is that virus scan blocks anything outgoing on port 25, which is used for e-mail, and prevents any program not on the "approved list" from sending e-mail. Thus, there is a good chance that your virus scan thinks your program is a worm trying to send out mass mailings against your will.
Hope this fixes the problem.
EthanS- Proposed as answer by mbostrom Wednesday, September 9, 2009 6:47 PM
Monday, August 7, 2006 4:42 PM -
hi,
i want to use my outlook email address (or any email account setup on the machine...) settings to send mails from my application.
specially to set the HOST in the SmtpClient, i want to pick it from the configured mail account.
how could that be done.
regards,
sharn722
Wednesday, October 4, 2006 10:12 AM -
if you already have a configured email account, you may not need to specify anything by code, CDO objects will use by default the current settings.Wednesday, October 4, 2006 1:35 PM
-
Josh I am still struggling with this problem
By looking at all the posts you guys have I am assuming you have found a solution and way to debug the problem
Could you please help me on this,
Thanks for your input.
I will really appreciate any help. I am trying to use my gmail account to send me an email to my hotmail account
Here is the code sinppet for your reference
**********************
MailMessage
mailMessage = new MailMessage(); try{
EmailResultTextBox.Text =
"Started @" + DateTime.Now + Environment.NewLine; SmtpClient client = new SmtpClient(SMPTPServerTextBox.Text.Trim()); // client.Host = SMPTPServerTextBox.Text.Trim(); string emailUserName = FromAddressEmailTextBox.Text.Trim(); string emailPassword = EmailPasswordTextBox.Text.Trim();client.UseDefaultCredentials =
false; //mailClient.UseDefaultCredentials = Falseclient.Credentials =
new NetworkCredential(emailUserName, emailPassword);client.EnableSsl =
true; string toAddress = ToAddressEmailTextBox.Text.Trim();mailMessage.To.Add(
new MailAddress(toAddress));mailMessage.From =
new MailAddress(emailUserName);mailMessage.Subject = SubjectTextBox.Text.Trim();
mailMessage.Body = EmailBodyTextBox.Text.Trim();
//Specifying the real SMTP Mail Server.client.DeliveryMethod =
SmtpDeliveryMethod.Network;EmailResultTextBox.Text +=
"Going to call send @" + DateTime.Now + Environment.NewLine;client.Send(mailMessage);
EmailResultTextBox.Text +=
"Successfully sent mail @" + DateTime.Now + Environment.NewLine; // Logger.LogInfo("Successfully Sent Email");}
catch (Exception ex){
EmailResultTextBox.Text +=
"Failed @" + DateTime.Now + Environment.NewLine;EmailResultTextBox.Text += ex.Message;
}
Tuesday, October 31, 2006 11:32 PM -
hey evreything was the same,
till i had installed mail enable program.
you can get it from : http://www.mailenable.com/download.asp then download > Standard Edition, feel free , it is free!ask me if more Question about my problem, my e-mail is blgnklc@gmail.com
Bilgin KILIÇ
my best forum in turkish: www.damlalar.com
just sharing my mood and knowledgeWednesday, November 1, 2006 6:46 AM -
Damn, thanks for the hint. That's exactly the problem I had. New McAffee features a port blocking engine that prevents outbounds to various known ports including smtp, irc, etc...Wednesday, November 8, 2006 9:03 PM
-
Hi.
I'm trying to send an e-mail from a winform. I want to send it from a hotmail account to any other domain's account. Is this possible?
Which SMTP server should I use?
I've tried this code.
System.Net.Mail.
MailMessage message = new System.Net.Mail.MailMessage();message.To.Add(
"parmas.pb@gmail.com");message.Subject =
"This is the Subject line";message.From =
new System.Net.Mail.MailAddress("account@hotmail.com");message.Body =
"This is the message's body.";System.Net.Mail.
SmtpClient smtp = new System.Net.Mail.SmtpClient("mail.hotmail.com");smtp.Credentials =
new System.Net.NetworkCredential("account", "password");smtp.Send(message);
I don't get any compiling errors but the sending-mail operation its timed out.
If anyone knows how to make this work out I will be really thankful.
Greetings & Happy New Year 2007.
Wednesday, January 3, 2007 7:37 PM -
Hi All,
I need your help regarding sending Email through Microsoft Exchange Server. Is there any code snippet or any .dll which will give me the brief idea?
As per my info Exchange server act as wrapper and invokes SMTP internally to send the mail. Outlook is client and been connected to exchange server. I don't want to install outlook on my machine and want to directly connect to exchange server which is located at company network.
C# code/snippet preferable
Could you Pls help me in doing this....
Thanks,
Ashish
Wednesday, January 24, 2007 6:13 AM -
simply use your exchange server as SMTP log in using the email account credentials and use any of the snnipets in this page.
Wednesday, January 24, 2007 2:12 PM -
Thanks a lot , it worksThursday, January 25, 2007 9:19 AM
-
I want to do the same job but I want to send attachments as well. Please help. Thanks in advance
- Proposed as answer by krishnasharma Monday, February 28, 2011 6:15 PM
Tuesday, March 20, 2007 8:57 AM -
Gmail works fine, but I could NEVER make hotmail and yahoo work. What is hotmail/yahoo's smtp server name? Or they just don't support it?Thursday, March 22, 2007 9:05 PM
-
Plese tell me how to make hotmail or yahoo work. Or, what's their smtp server name?Thursday, March 22, 2007 9:08 PM
-
Nice example.
But, how can I send embedded images in the e-mail, using the Exchange Server mailbox over http using WebDAV?
Many thanksThursday, April 5, 2007 12:41 PM -
I have five text box , I want to send textbox value send by mail to particular email Address,How can I send value of text box directly by mailIn VS2005 using C#Tuesday, June 5, 2007 6:58 AM
-
I have try the following code snippet
help where is the proble,i have received an error
unavailable textbox,cant reley the mail to this id
i have specified localhost as the smtp mail server,is any other name?
<%@ Import Namespace="System.Web.Mail" %>
<html>
<script language="VB" runat="server">
Sub Page_Load(Sender As Object, E As EventArgs)
Dim msg as New MailMessage()
msg.To = "hajaworld@gmail.com"
msg.From = "hajaworld@gmail.com"
msg.Subject = "test"
'msg.BodyFormat = MailFormat.Html
msg.BodyFormat = MailFormat.Text
msg.Body = "hi"
SmtpMail.SmtpServer = "localhost"
SmtpMail.Send(msg)
msg = Nothing
lblMsg.Text = "An Email has been send to " & "hajaworld@gmail.com"
End Sub
</script>
<body style="font: 10pt verdana">
<form runat="server">
<asp:Label id=lblMsg runat="Server" /> </form>
</body>
</html>Monday, July 2, 2007 6:51 AM -
Hi josh I tried to send mail using code but I am getting error .Fields does not exist, although I am using VS2005 C# and I have added ref of CDO from library.
Please give me suggestion.
Thanks in advance for showing the way.
Regards,
JeevanWednesday, July 18, 2007 12:04 PM -
Were you able to get this working with basic authentication with IIS 6?Thursday, July 19, 2007 9:01 PM
-
I have used form authentication in my web application. and I am using VS 2005 with C#.
This is the code i have written.It is not giving any exception. but still the mail is not going.
try
{
//creating new mail.
System.Net.Mail.MailMessage newmail = new System.Net.Mail.MailMessage();
//setting mail parameters
newmail.To.Add("sendme@gmail.com");
newmail.From = new System.Net.Mail.MailAddress("xyz.abc@gmail.com", "XYZ", System.Text.Encoding.UTF8);
newmail.Subject = "Lost id or password";
//writing mail body
String mailbodytext = "This is a auto generated mail.";
newmail.Body = mailbodytext;
//sending the mail.
System.Net.Mail.SmtpClient theClient = new System.Net.Mail.SmtpClient();
System.Net.NetworkCredential theCredential = new System.Net.NetworkCredential("abcdef@gmail.com", "abcabc");
theClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
theClient.Port = 465;
theClient.Host="smtp.gmail.com";
theClient.EnableSsl = true;
theClient.UseDefaultCredentials = false;
theClient.Credentials = theCredential;
object userstate = newmail;
theClient.SendAsync(newmail,userstate);
//theClient.Send(newmail);
}
catch (System.Net.Mail.SmtpException smex)
{
Console.Write(smex.Message,"Send Mail Error");
}
catch (System.Exception ex)
{
Console.Write(ex.Message);
}Friday, July 20, 2007 5:55 AM -
I'm having a similar issue. I believe that this is a bug in the .NET framework.
The deprecated CDONT example works fine, however.Friday, July 20, 2007 11:14 PM -
Hello,
I tried your code and it didn't work, It compiled fine, but it gave me a message that it couldn't connect to the server and the code broke at this line System.Web.Mail.SmtpMail.Send(message); What can be the problem? I'm just trying to send an email in a c# windows form. do I have to modify something in code?, Sorry if this is easy, but I'm new to .NET
this what I had:
System.Web.Mail.MailMessage message = new System.Web.Mail.MailMessage();
message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "SmtpHostUserName");
message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "SmtpHostPassword");
message.From = "from e-mail";
message.To = "to e-mail";
message.Subject = "Message Subject";
message.Body = "Message Body";
System.Web.Mail.SmtpMail.SmtpServer = "SMTP Server Address";
System.Web.Mail.SmtpMail.Send(message);Wednesday, August 1, 2007 6:55 PM -
please try the code i put at page 2, if doenst work either check for the antivirus software is not blocking ur app to send the email, and check if the firewall is not blocking port 25.
Wednesday, August 1, 2007 9:29 PM -
Hi,
i want to send the MailMessage Object via HTTP (Webrequest). This is neccesary for a S/MIME communication over HTTP (AS2).
I get a positive response (MDN) but the target File simple contains "System.Net.Mail.MailMessage". Since the Message is a multipart Message with signatur and is crypted i can not create a simple String-Email as shown earlyer in this Thread.
I use following code:
MailMessage Msg = new MailMessage();
Msg.From = new MailAddress("email@provider.de");
Msg.To.Add(" email@provider.de");
Msg.Subject = "Betreff";
Uri uri = new Uri("http://127.0.0.1ort/");
WebRequest wReq = WebRequest.Create(uri);
wReq.Method = "PUT";
StreamWriter sw = new StreamWriter(wReq.GetRequestStream());
sw.Write(Msg);here i want to send the hole MailMassege but get only "System.Net.Mail.MailMessage"
sw.Close();
WebResponse wResp = wReq.GetResponse();
StreamReader sr = new StreamReader(wResp.GetResponseStream());
String response = sr.ReadToEnd();
sr.Close();Any sugestions?
Thursday, August 23, 2007 6:26 PM -
Bad news, if u didnt pay for yahoo smpt you are not going to be able to use their smtp, better to find another free one, like gmail i belive there are some examples on previous posts...
thanks.
Friday, November 23, 2007 11:25 PM -
i m trying to send mail using win application, i m able to send mail using gmail smtp but not able to send using any of the yahoo, rediff, hotmail or anyother smtp server. On using any of these server I am getting smtp exception(The SMTP server requires a secure connection or the client was not authenticated).Is this doing some extra setting for sending the mail using these ? if yes plz tell me or they are paid smtp server? Is this possible to get that which one is paid smtp server.If yes, please tell, how?
Thanks,
Saturday, November 24, 2007 3:35 PM -
helloo...
i find same code about send mail using C# , but it dosn't work
so can you tell me if i useing VBasic code or ASP.net code how do i do that ( send the mail ) I try many way but not work.
Sunday, December 16, 2007 10:34 PM -
I read some posts and it seems many of us have problems with getting that Smtp server working. I came up with a working sollution to your problems but you will have to use local smtp server.
You have to install IIS (which some of you already have installed because of Visual Studio), and after this go to Administrative tools, IIS and setup the Virtual Smtp Server to grant permission to localhost.
After this you can test it:
(example in C# .NET 2.0)
Code BlockSmtpClient g = new SmtpClient();
g.Host = "localhost";
g.Send("from@host.com", "recepient@host.com", "testsubject", "message");
PS: For the "from" parameter you can use any email address you like.
PPS: If you send to a yahoo address, please check the spam folderTuesday, January 1, 2008 2:55 PM -
I have try ur code...like this
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("nikunjganatra007@gmail.com");
message.Subject = "This is the Subject line";
message.From = new System.Net.Mail.MailAddress("projecttest@proseon.com");
message.Body = "This is the message body";
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("127.0.0.1",25);
smtp.Send(message);
here nikunjganatra007@gmail.com is my personal id, and projecttest@proseon.com is my compnay's id.
is there any SMTP settings/configuration require....
it throws exeception like this:
System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: An established connection was aborted by the software in your host machine at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) --- End of inner exception stack trace --- at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout) at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback) at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback) at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port) at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port) at System.Net.Mail.SmtpClient.GetConnection() at System.Net.Mail.SmtpClient.Send(MailMessage message) --- End of inner exception stack trace --- at System.Net.Mail.SmtpClient.Send(MailMessage message) at _Default.Button2_Click(Object sender, EventArgs e) in c:\WebSites\WebSite1\Default.aspx.cs:line 109Monday, February 11, 2008 7:10 AM -
hi, I m also getting same problem in sending mail...
if u have found solution then plz send me on nikunjganatra2003@gmail.com
thanks.Monday, February 11, 2008 7:20 AM -
Dear Mohamed,
I am running MONO.NET on my Linux server. I was just wondering if you could give me an advice about sending mail from MONO. The compilation is without problems, but after there is Error message 500:
I have tried this several options see bellow:
http://tadmin.eutree.eu/Pavel/Email5/
http://tadmin.eutree.eu/Pavel/Email8/ (your code)
and there is still the same problem Error 500 :-(
Thanks for anz help
Pavel
---------------------------------
No such host is known
Description: Error processing request.
Error Message: HTTP 500. System.Net.Sockets.SocketException: No such host is known
Stack Trace:
System.Net.Sockets.SocketException: No such host is known
at System.Net.Dns.GetHostByName (System.String hostName) [0x00000]
at System.Net.Sockets.TcpClient.Connect (System.String hostname, Int32 port) [0x00000]
at System.Net.Sockets.TcpClient..ctor (System.String hostname, Int32 port) [0x00000]
at System.Web.Mail.SmtpClient.Connect () [0x00000]
at System.Web.Mail.SmtpClient.StartSend (System.Web.Mail.MailMessageWrapper msg) [0x00000]
at System.Web.Mail.SmtpClient.Send (System.Web.Mail.MailMessageWrapper msg) [0x00000]
at System.Web.Mail.SmtpMail.Send (System.Web.Mail.MailMessage message) [0x00000]
----------------Sunday, May 4, 2008 2:53 PM -
ok lets get this clear
1) Not all service providers (email) will allow you to use their SMTP services unless you pay for it, or are allowed to send email via their services for obvious reasons (security, spam prevention etc... etc..)
2) There are some free email providers that allow you to use their SMTP as long as you have an email address with them, such as gmail and other providers
3) Settings differ from providers, some use SSL like google and on a different port, but commonly and across all SMTP providers, you MUST provide credentials (your email address on that account and password) so they can authenticate you successfully
4) Whilst you could set up your own POP3 services on your own computer, you still need to configure it to use relay's, domain's/forwarding etc... etc...
Sunday, May 4, 2008 9:54 PMModerator -
Hi,
This is the code in webdav to send mail using exchange server
public void Sendmail()
{
System.Net.HttpWebRequest PUTRequest;
System.Net.HttpWebRequest PUTRequest1;
System.Net.WebResponse PUTResponse;
System.Net.WebResponse PUTResponse1;
System.Net.HttpWebRequest PROPPATCHRequest;
System.Net.WebResponse PROPPATCHResponse;
System.Net.HttpWebRequest MOVERequest;
System.Net.WebResponse MOVEResponse;
System.Net.CredentialCache MyCredentialCache;
string strMailboxURI = "http://Your exchange server/exchange/";
string strSubURI = "http://Your exchange server/exchange/";
string strTempURI = "http://Your exchange server/exchange/";
string strServer = "Your exchange server";
string strPassword = "your password";
string strDomain = "your domain";
string strAlias = "your user name";
string strTo = "to whom u want to send";
string strSubject = "Test";
string strText = "This message was sent using WebDAV";
string strBody = "";
byte[] bytes = null;
System.IO.Stream PUTRequestStream = null;
try
{
// Build the mailbox URI.strMailboxURI = "http://" + strServer + "/exchange/" + strAlias;
// Build the submission URI for the message. If Secure
// Sockets Layer (SSL) is set up on the server, use
// "https://" instead of "http://".strSubURI = "http://" + strServer + "/exchange/" + strAlias +
"/##DavMailSubmissionURI##/";
// Build the temporary URI for the message. If SSL is set
// up on the server, use "https://" instead of "http://".
strTempURI = "http://" + strServer + "/exchange/" + strAlias + "/drafts/" +
strSubject + ".eml/";
// Construct the RFC 822 formatted body of the PUT request.
// Note: If the From: header is included here,
// the MOVE method request will return a
// 403 (Forbidden) status. The From address will
// be generated by the Exchange server.
strBody = "To: " + strTo + "\n" +
"Subject: " + strSubject + "\n" +
"Date: " + System.DateTime.Now +
"X-Mailer: test mailer" + "\n" +
"MIME-Version: 1.0" + "\n" +
"Content-Type: text/plain;" + "\n" +
"Charset = \"iso-8859-1\"" + "\n" +
"Content-Transfer-Encoding: 7bit" + "\n" +
"\n" + strText;
// Create a new CredentialCache object and fill it with the network
// credentials required to access the server.
MyCredentialCache = new System.Net.CredentialCache();
MyCredentialCache.Add(new System.Uri(strMailboxURI),
"Basic",
new System.Net.NetworkCredential(strAlias, strPassword, strDomain)
);
// Create the HttpWebRequest object.
PUTRequest = (System.Net.HttpWebRequest)HttpWebRequest.Create(strTempURI);
// Add the network credentials to the request.
PUTRequest.Credentials = MyCredentialCache;
// Specify the PUT method.
PUTRequest.Method = "PUT";
// Encode the body using UTF-8.
bytes = Encoding.UTF8.GetBytes((string)strBody);
// Set the content header length. This must be
// done before writing data to the request stream.
PUTRequest.ContentLength = bytes.Length;
// Get a reference to the request stream.
PUTRequestStream = PUTRequest.GetRequestStream();
// Write the message body to the request stream.
PUTRequestStream.Write(bytes, 0, bytes.Length);
// Close the Stream object to release the connection
// for further use.
PUTRequestStream.Close();
// Set the Content-Type header to the RFC 822 message format.
PUTRequest.ContentType = "message/rfc822";
// PUT the message in the Drafts folder of the
// sender's mailbox.
PUTResponse = (System.Net.HttpWebResponse)PUTRequest.GetResponse();
// Create the HttpWebRequest object.
MOVERequest = (System.Net.HttpWebRequest)HttpWebRequest.Create(strTempURI);
// Add the network credentials to the request.
MOVERequest.Credentials = MyCredentialCache;
// Specify the MOVE method.
MOVERequest.Method = "MOVE";
// Set the Destination header to the
// mail submission URI.
MOVERequest.Headers.Add("Destination", strSubURI);
// Send the message by moving it from the Drafts folder of the
// sender's mailbox to the mail submission URI.
MOVEResponse = (System.Net.HttpWebResponse)MOVERequest.GetResponse();
Console.WriteLine("Message successfully sent.");
// Clean up.
PUTResponse.Close();
MOVEResponse.Close();
}
catch (Exception ex)
{
// Catch any exceptions. Any error codes from the PUT
// or MOVE method requests on the server will be caught
// here, also.
Console.WriteLine(ex.Message);
}
}
Pranaya- Edited by Pranaybsingh Tuesday, October 7, 2008 10:03 AM
Tuesday, October 7, 2008 10:00 AM -
This code is correct. Thanks a lot!Tuesday, November 25, 2008 3:16 PM
-
i have used the code above and it works (i think)
wht wood i have to change to send lots of emails relly fast (eg. if i was spaming someone)
sam eden
try SAIO v1.0 beta go to sites.google.com/site/sameden2Tuesday, March 3, 2009 7:10 PM -
spamming is not good at all and such discussions would not be allowed at all. but to send bulkemails totally depends on the network speed and how fast your system is - nothing else.
Need 2 be back @ MS - MS All the way! Follower since 1995 MS Super Evangelist| MSDN Forums Moderator- Marked as answer by ahmedilyasModerator Tuesday, March 3, 2009 7:18 PM
Tuesday, March 3, 2009 7:18 PMModerator -
i now i was useing it as an example i need it for sending out lots of emails t 1 email adresss
try SAIO v1.0 beta go to sites.google.com/site/sameden2Tuesday, March 3, 2009 7:35 PM -
ThanksFriday, April 17, 2009 5:58 PM
-
What if the SMTP server requires authentication?
Giggig Enterprises http://www.giggig.co.uk/Saturday, June 6, 2009 9:45 PM -
-
Wednesday, June 17, 2009 4:48 AM
-
I am posting this because though there is lot much discussed, I couldn't see the code snippet for sending emails through exchange server or
https:// servers.
SmtpClient smtp = new SmtpClient(); smtp.Port = 25; // specify the smtp port smtp.Host = "Just your host name, no need of preceding with smtp. ect"; // specify the name/ip address of the host smtp.Credentials = new NetworkCredential(usr, passwd); // authenticate // message MailMessage email_msg = new MailMessage(); email_msg.To.Add("abc@domain.com"); email_msg.From = new MailAddress("xyz@some.com"); email_msg.Subject = "test mail..."; email_msg.Body = "Hello world!!!"; email_msg.IsBodyHtml = false; smtp.Send(email_msg); // now send the messageOnly thing that one should remember not to set EnableSsl = true;.
AnandFriday, June 19, 2009 5:00 AM -
Is it possible to programatically bring up the default email program on a computer and automatically populate the To, Message, Subject, and Attachment fields?
Peter Harnish- Proposed as answer by myrocode Tuesday, September 15, 2009 8:34 AM
Wednesday, August 5, 2009 5:48 PM -
I wrote an article on how you can send emails (bulk mail is also supported) using c#. Yust copy and paste the snippet.
http://www.myrocode.com/post/2009/09/15/Code-Snippet-Send-Bulk-Emails-in-C.aspx
you can also add attachment using:
MailAttachment attachment = new MailAttachment( Server.MapPath( "test.txt" ) ); //create the attachment
mail.Attachments.Add( attachment ); //add the attachmentTuesday, September 15, 2009 8:27 AM -
Is it possible to programatically bring up the default email program on a computer and automatically populate the To, Message, Subject, and Attachment fields?
Peter Harnish
if you are developing an asp.net application you can javascript to open up the default email program and populate To, Message,Subject, but you cannot add attachments.
here's a a method written in c# :
private void OpenOutlook(string to, string subject, string cc, string bcc, string body)
{
// replace for the newline \n \r
body = body.Replace("\r", "%0D").Replace("\n", "%0A");
// build the js
string js = String.Format(@"
window.onload = function () {{
var to = '{0}';
var cc = '{1}';
var bcc = '{2}';
var body = '{3}';
var subject = '{4}';
var response = 'mailto:'+ to + '?subject='+subject+'&body='+body+'&cc='+cc+'&bcc='+bcc;
location.href = response;
window.close();
}}
", to, cc, bcc, body, subject);
// register the client js block
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "outlook", js, true);
}
remember to handler the js's escape characters- Proposed as answer by myrocode Tuesday, September 15, 2009 9:27 AM
Tuesday, September 15, 2009 9:27 AM -
Hi There?
I hope this code snippet I think it may also help u...though meant for SMTP protocol e-mail settings:
MailMessage mail = new MailMessage();
mail.To.Add("EMAIL REMOVED");
mail.From = new MailAddress("EMAIL REMOVED");
mail.Subject = "Test Email";
string Body = "Welcome to CodeDigest.Com!!";
mail.Body = Body;
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["SMTP"];
smtp.Send(mail);
Kind Regards
Sagini
Thursday, October 8, 2009 9:21 AM -
Here's something that i wrote on my blog http://www.stjhimy.com/2009/12/13/how-to-send-an-email-using-c/
Hope it helps : )Sunday, December 13, 2009 10:26 PM -
Thank you very much . nice code ..Monday, January 18, 2010 10:54 AM
-
Great code .. codemaster ... i was in search of that code only ... thnx alot man .. keep it up ...Thursday, January 28, 2010 7:49 PM
-
Can you please tell how to add an attachment to this mailTuesday, July 6, 2010 12:59 PM
-
Pranaybsingh's method is really good for exchange servers - I used it and it worked perfectly. Thought people looking for the same solution should know.Friday, July 23, 2010 8:29 AM
-
find a simple smtp mail in c#
http://csharp.net-informations.com/communications/csharp-smtp-mail.htm
gev.
Sunday, August 29, 2010 5:28 AM -
hi,
i have a query with regard to changing the email to the displayname.
when i specify the To address and From address as follows and send the mail.
email_msg.To.Add("abc@microsoft.com");
email_msg.From = new MailAddress("xyz@microsoft.com");
I see the Outlook changing the To address to the display name but my from address is still shown as "xyz@microsoft.com" on the email.
why is the outlook rendering only the To address and not the From address. Both(To and From addresses)
are valid Ids
Tuesday, October 5, 2010 2:42 AM -
The Ultimate SMTP library for .NET Framework may help you. Please see this code:
const string serverName = "myserver" ;
const string user = "name@domain.com " ;
const string password = "mytestpassword" ;
const int port = 465;
const SecurityMode securityMode = SecurityMode.Implicit;
SmtpClient client = new SmtpClient();
try
{
MailMessage mmMessage = new MailMessage();
mmMessage.From.Add( "from@thedomain.com " );
mmMessage.To.Add( "name@domain.com " );
mmMessage.To.Add( "someone@domain.com " );
mmMessage.Cc.Add( "someone2@domain.com " );
mmMessage.Bcc.Add( "someone3@domain.com " );
mmMessage.Subject = "Test Subject" ;
mmMessage.BodyText = "Test Content" ;
Console.WriteLine( "Connecting SMTP server: {0}:{1}..." , serverName, port);
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
Console.WriteLine( "Logging in as {0}..." , user);
client.Authenticate(user, password);
Console.WriteLine( "Sending mail message..." );
client.Send(mmMessage);
Console.WriteLine( "Message sent..." );
// Disconnect.
Console.WriteLine( "Disconnecting..." );
client.Disconnect();
}
catch (SmtpException smtpExc)
{
MessageBox.Show( string .Format( "An SMTP error occurred: {0}, ErrorStatus: {1}" , smtpExc.Message, smtpExc.Status));
}
catch (Exception exc)
{
MessageBox.Show( string .Format( "An error occurred: {0}" , exc.Message));
}
More examples can be found on Ultimate SMTP's blog .
Wednesday, October 6, 2010 8:37 PM -
ThanksThursday, October 21, 2010 7:54 AM
-
hey mohamed,
this above code will work in C++?
because this line
system.Web.Mail.MailMessage message=new System.Web.Mail.MailMessage();
doesnt wrk in c++ as in web we dnt have mail to select
Monday, December 13, 2010 8:54 PM -
hi josh.
man i need ur help this code gives an error
error C3673: 'System::Net::Mail::MailMessage' : class does not have a copy-constructor
tell me what to do .
i made few changes n im tryin to run this code in visual c++
Tuesday, December 14, 2010 9:54 PM -
hi ,
look this http://www.codeproject.com/KB/IP/SendMailUsingGmailAccount.aspx
I find this article very nice.
Good Luck
Wednesday, December 15, 2010 3:44 PM -
MailMessage MailMesaji = new MailMessage();
MailMesaji.Subject = "hai";
MailMesaji.Body = "how are u";
MailMesaji.BodyEncoding = Encoding.GetEncoding("Windows-1254");
MailMesaji.From = new MailAddress("mr.srinu369@gmail.com");
MailMesaji.To.Add(new MailAddress("mr.srinu369@gmail.com"));
System.Net.Mail.SmtpClient Smtp = new SmtpClient();
Smtp.Host = "smtp.gmail.com";
Smtp.Port = 25;
Smtp.EnableSsl = true;
Smtp.Credentials = new System.Net.NetworkCredential("mr.srinu369@gmail.com", "tulasicnu");
Smtp.Send(MailMesaji);i wrote like this but i got an like Failure sending mail.how can i rectify this problem and i am awaiting for modification and apply to page.
So please forward the correct answer to this blog.
Friday, December 17, 2010 11:04 AM -
string senderEmail =ConfigurationSettings.AppSettings["SenderEmail"].ToString(); string senderPassword = ConfigurationSettings.AppSettings["SenderPassword"].ToString(); string mailHost = ConfigurationSettings.AppSettings["EmailHost"].ToString(); if (senderEmail.Trim().Equals(string.Empty) || senderPassword.Trim().Equals(string.Empty) || mailHost.Trim().Equals(string.Empty)) { MessageBox.Show("Configure Mail Setting or contact support team"); return; } try { MailMessage mail = new MailMessage(); mail.To.Add(Email); mail.From = new MailAddress(Email); mail.Subject = "Your Password"; mail.Body = "Dear User
As Per your request we are sending you the latest password. your account info on Evolution is as
User Name='" + txtUserName.Text + "'
Password=' " + Password + "'
Thanks Evolution Support Team"; mail.IsBodyHtml = true; //mail.Attachments.Add(new Attachment(Path + ".pdf")); SmtpClient smtp = new SmtpClient(); smtp.Host = mailHost; //Or Your SMTP Server Address smtp.Credentials = new System.Net.NetworkCredential (senderEmail, senderPassword); //Or your Smtp Email ID and Password smtp.EnableSsl = true; smtp.Send(mail); MessageBox.Show("Password sent to: '" + Email + "'"); } catch { MessageBox.Show("Email not send successfully"); } } Enjoy this code You just need to set username and password in .config fill- Proposed as answer by Faisal Hayat Thursday, January 27, 2011 2:04 PM
Thursday, January 27, 2011 2:04 PM -
Hi anjali..
pls same help.
just i want code for send a mail..
Monday, February 28, 2011 6:17 PM -
using System.IO
using System.Net.Mail;
using System.Net.Mime;//use the namespaces to invoke related classes
private void sendMail_Click(object sender, EventArgs e)
{MailMessage MailObj = new MailMessage("From", "To", "Subject", "Body");
// MailMessage MailObj = new MailMessage(textBox1, textBox2, textBox3, textBox4); or you may also do this, insted of above
SmtpClient SMPTobj = new SmtpClient("smtp.xyz.com"); //your outgoing server address
SMPTobj.EnableSsl = true;
SMPTobj.Credentials = new System.Net.NetworkCredential("your mail id here", "password");
try
{
SMPTobj.Send(MailObj);
}
catch (Exception ex)
{
label.Text = ex.ToString();
}}
Tuesday, June 28, 2011 4:57 PM -
if i want to send bulk email then how to write code for that
Thursday, August 25, 2011 6:02 AM -
Use php instead of ASP.net. It does not include an over complicated process for sending emails, and all webhost sites serve php cheaper and for free. For example, to send an email using php use this function :
mail(to, subject, body, [header]);
You may use a series of email addresses, separated by commas. Yes! they can be php variables. The [hearder] parameter is optional. Game over. Again guys, this just makes WAY more sense in php. Look at that compared to all the long elaborate code others posted with c#. I love MS, dont get me wrong. I even started with ASP.net, but that line of script speaks for itself.
proof is in the pudding.
Monday, September 19, 2011 4:06 PM -
Here is another sample for sending email using C# :
using System.Net; using System.Net.Mail; var fromAddress = new MailAddress("from@live.com", "From Name"); var toAddress = new MailAddress("to@example.com", "To Name"); const string fromPassword = "fromPassword"; const string subject = "Subject"; const string body = "Body"; var smtp = new SmtpClient { Host = "smtp.live.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) { smtp.Send(message); }
-- Mreza- Proposed as answer by william_karma Monday, June 11, 2012 12:09 AM
Friday, December 23, 2011 7:36 PM -
Hello ,
this a nice article , it can help
http://www.codeproject.com/KB/vb/SendMail.aspx
thank...
Wednesday, December 28, 2011 4:48 PM -
This really helps! But I need help now. I'm trying to get the email to send me some of the code within the email. I want it to send me what they type into a certain prompt, but i'm unsure as how to code that into the email code. Could you help?
Wednesday, September 5, 2012 6:25 PM -
Josh,
this snippet saved me loads of time. This totally worked.
I used this in my "WriteToEventLog". So that every time an exception/error occurs, my program would write to event log (i used stacktrace), then send me an email with a brief message.
Thanks mate.
Tuesday, December 4, 2012 6:13 PM