I am using C#.NET 4.0 and would like to send an email to an address with a subject and a body, the body will contain some information from a few text-boxes in my application.
I have little to no experience with sending emails in C#, so any help here would be appreciated. All I know is that you have to use the System.Net.Mail namespace. I tried this code but it gave an "Failure sending Mail" exception.
new SmtpClient("smtp.server.com", 25).Send("test@hotmail.com",
"test@gmail.com",
"subject",
"body");
What is wrong with the above code? Furthermore, is there any better way to 开发者_运维知识库send the email?
Probably your authentication (credentials) or servername/port is not correct.
Try this:
MailMessage mailMsg = new MailMessage();
mailMsg.To.Add("test@hotmail.com");
// From
MailAddress mailAddress = new MailAddress("you@hotmail.com");
mailMsg.From = mailAddress;
// Subject and Body
mailMsg.Subject = "subject";
mailMsg.Body = "body";
// Init SmtpClient and send on port 587 in my case. (Usual=port25)
SmtpClient smtpClient = new SmtpClient("mailserver", 587);
System.Net.NetworkCredential credentials =
new System.Net.NetworkCredential("username", "password");
smtpClient.Credentials = credentials;
smtpClient.Send(mailMsg);
you cannot leave this string:
smtp.server.com
you should have there the name of your smtp server, usually something like mail.yourcompanyname.com or smtp.yourcompanyname.com
Is smtp.server.com really an SMTP server? You need to replace that with a real one. Your ISP probably provides you one, but it will likely only relay for emails originating from an address that your ISP owns.
I have worked with three well known ISP’s to host my client’s websites. All three ISP's instructed me to use “localhost” as the smtp server name.
Add this:
SmtpServer.EnableSsl = true;
精彩评论