Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

.net - C# how to send email?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...