How do I send mail using C#?
- Does anyone have a code snippet that shows how to send mail from c#?
Odpovědi
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);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:
If you want the shortest way: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,- 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- Označen jako odpověďahmedilyasMVP, Moderátor3. března 2009 19:18
Všechny reakce
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);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:
If you want the shortest way: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,- 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.zip - 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). 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();
}- 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.
- 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); The system.net.mail class is the recomended way to handle mail sends no matter what sort of application you are building.
- Thanks, Josh!
- 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 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 lotI 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 again- Hi,
I have McAffee Scan On-Access disabled and problem is gone
greetz 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,
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
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
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
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 ???
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 .....
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.
>is it enough ???
LOL

I hope it is, ...I will try in a few moment.
Bye
Unfortunately, it does not work.
After 100 seconds an operation timeout exception is thrown (it is an smtpException).
Here is the code:
if(_toAddresses.Count==0) throw new EmailNotifierException(this,n,"No recipients specified."); SmtpClient smtpClient = new SmtpClient();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); }i'm succeeded to connect to Exchange server as SMTP
not need this code just use the simple smtp code and go on
//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);
}
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!
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.
- 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?
Marc 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.
- 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).
Marc 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();
}
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.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.
- 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);
}
}
} 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.- 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.
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";}
}
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- Navržen jako odpověďmbostrom 9. září 2009 18:47
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
- 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.
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;
}
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 knowledge- 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...
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.
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
simply use your exchange server as SMTP log in using the email account credentials and use any of the snnipets in this page.
- Thanks a lot , it works

- I want to do the same job but I want to send attachments as well. Please help. Thanks in advance
- 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?
- Plese tell me how to make hotmail or yahoo work. Or, what's their smtp server name?
- Nice example.
But, how can I send embedded images in the e-mail, using the Exchange Server mailbox over http using WebDAV?
Many thanks
- 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#
- 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> - 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,
Jeevan - Were you able to get this working with basic authentication with IIS 6?
- 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);
} - I'm having a similar issue. I believe that this is a bug in the .NET framework.
The deprecated CDONT example works fine, however. - 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); 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.
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.1
ort/");
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?
- hi...
could you tell me how to find my smtphost.??
i changed ur code to this ... added whatever i needed..
private void button1_Click(object sender, EventArgs e)
{
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("sreeks_13@yahoo.co.in");
message.Subject = "This is the Subject line";
message.From = new System.Net.Mail.MailAddress("sreeks13@gmail.com");
message.Body = "This is the message body";
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.yahoo.com");
smtp.Send(message);
}
but i dont know for some reason doesnt work ..
i wonder if i am using the correct smtp client i am not sure what exactly to do there. 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.
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,
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.
- 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)
Hope this solves your problems!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 folder
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 109
hi, I m also getting same problem in sending mail...
if u have found solution then plz send me on nikunjganatra2003@gmail.com
thanks.- 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]
---------------- 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...
- 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- UpravenýPranaybsingh 7. října 2008 10:03
- This code is correct. Thanks a lot!
- 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/sameden2 - 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- Označen jako odpověďahmedilyasMVP, Moderátor3. března 2009 19:18
- 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/sameden2 - Thanks
- What if the SMTP server requires authentication?
Giggig Enterprises http://www.giggig.co.uk/ - Navržen jako odpověďGiggig guy 13. června 2009 12:15
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 <br/>https:// servers. <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>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 message
Only thing that one should remember not to set EnableSsl = true;.
Anand- 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- Navržen jako odpověďmyrocode 15. září 2009 8:34
- 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 attachment 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- Navržen jako odpověďmyrocode 15. září 2009 9:27
- 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
- Just download this SMTP Component for .NET and follow its tutorial

