我想编码在asp.net中发送邮件和消息

时间:2017-09-21 09:21:07

标签: asp.net

这是我的代码:

string from = "rashmi@example.com";
string to = "rashmi@example.com";
string mailSubject = "mail demo";
string mailBody = "mail sent successfully";

MailMessage mess = new MailMessage(from, to, mailSubject, mailBody);
mess.IsBodyHtml = true;

SmtpClient emailClient = new SmtpClient("192.168.43.1", 25); //Server ip & port
emailClient.UseDefaultCredentials = false;
emailClient.Credentials = new System.Net.NetworkCredential("rashmi@example.com", "****password****");

try
{
   emailClient.Send(mess);
   Response.Write("message sent");
}
catch (Exception ex)
{
    Response.Write("Exception caught in CreateTestMessage1(): {0}"+ ex.ToString());
}

但是我收到了这个错误:

  

CreateTestMessage1()中捕获到异常:{0} System.Net.Mail.SmtpException:服务不可用,关闭传输通道。服务器响应为:无法连接到SMTP服务器192.168.43.1(192.168.43.1:25),连接错误10061

     

在System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)上   在System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
  在System.Net.Mail.SmtpClient.GetConnection()
  在System.Net.Mail.SmtpClient.Send(MailMessage消息)的mail_demo_project.register_mail_demo.submit_Click(Object sender,EventArgs e)中的e:\ dot net \ projects \ mail演示项目\ mail demo project \ register_mail_demo.aspx.cs:第53行   错误发生...

1 个答案:

答案 0 :(得分:0)

使用此代码发送电子邮件:

string From = "fromemailaddress@gmail.com";
        MailAddress mailAddress = new MailAddress(From, "Contact Us");

        MailMessage mailMessage = new MailMessage();
        mailMessage.To.Add("toemailaddress@gmail.com");
        mailMessage.From = mailAddress;
        mailMessage.Subject = Txt_Subject.Text;

        string mailBody = "User Email: " + Txt_msg.Text + "<br/> User Name: " + Txt_Name.Text + "<br/> Message: " + Txt_msg.Text  ;

        mailMessage.Body = mailBody;
        mailMessage.Priority = MailPriority.Normal;
        mailMessage.IsBodyHtml = true;

        System.Net.NetworkCredential credential = new System.Net.NetworkCredential(From, "password");

        SmtpClient smtpClient = new SmtpClient();
        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtpClient.EnableSsl = false;
        smtpClient.Host = "smtp.gmail.com";
        smtpClient.Port = 587;
        smtpClient.UseDefaultCredentials = true;
        smtpClient.Credentials = credential;

        smtpClient.Send(mailMessage);

并且您必须在安全部分的gmail帐户中进行一些安全性修改:允许安全性较低的应用:是