【问题标题】:How to send email to gmail using SMTPclient in C#?如何在 C# 中使用 SMTPclient 向 gmail 发送电子邮件?
【发布时间】:2011-08-07 16:36:34
【问题描述】:

我正在使用outlook 2003 和visual studio 2008。我想开发一个将电子邮件发送到任何域的应用程序。但是当我尝试向 gmail、hotmail 等发送电子邮件时,我的代码失败了。实际上所有的邮件都存储在 C:\Inetpub\mailroot\Queue 目录中。请帮助我如何将电子邮件发送到 gmail、hotmail a/c。

提前致谢

代码是

System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("sumitdawar@hotmail.com");
message.To.Add("sumitdawar@gmail.com");            
message.Subject = "This is sample mail";
message.From = new System.Net.Mail.MailAddress("Sumit.Dhingra@niit.com");
message.Body = "this is the message body";


System.Net.Mail.SmtpClient sss = new System.Net.Mail.SmtpClient("HO-KKJ-MAIL.in.niit.com");
sss.UseDefaultCredentials = false;
sss.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
sss.Credentials = new System.Net.NetworkCredential("Sumit.Dhingrar", "password","domain");

【问题讨论】:

  • 您的凭据是否正确?您收到任何错误消息吗?

标签: c# .net-3.5 outlook-2003


【解决方案1】:

这是在C# 中使用Gmail 发送电子邮件的一个很好的示例

string from = me@gmail.com; //Replace this with your own correct Gmail Address

string to = you@gmail.com //Replace this with the Email Address to whom you want to send the mail

System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
 mail.To.Add(to);
 mail.From = new MailAddress(from, "One Ghost" , System.Text.Encoding.UTF8);
mail.Subject = "This is a test mail" ;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = "This is Email Body Text";
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true ;
mail.Priority = MailPriority.High;

SmtpClient client = new SmtpClient();
//Add the Creddentials- use your own email id and password

 client.Credentials = new System.Net.NetworkCredential(from, "Password");

client.Port = 587; // Gmail works on this port
client.Host = "smtp.gmail.com";
client.EnableSsl = true; //Gmail works on Server Secured Layer
       try
        {
            client.Send(mail);
        }
        catch (Exception ex) 
        {
            Exception ex2 = ex;
            string errorMessage = string.Empty; 
            while (ex2 != null)
            {
                errorMessage += ex2.ToString();
                ex2 = ex2.InnerException;
            }
   HttpContext.Current.Response.Write(errorMessage );
        } // end try 

你确定

message.From = new System.Net.Mail.MailAddress("Sumit.Dhingra@niit.com");

对吗?这个方法有这样的重载吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 2021-06-23
    相关资源
    最近更新 更多