无法在asp.net中发送mailmessage

时间:2014-08-28 07:37:02

标签: c# asp.net .net mailmessage

以下代码无法向客户发送电子邮件,也不会抛出任何异常。代码它不发送任何电子邮件或异常但已执行。我对asp.net完全是新的。有人可以帮我解决问题。

代码:

try
{
    String userName = "ramesh";
    String passWord = "123456";
    String sendr = "ramesh@gmail.com";
    String recer = "customer@yahoo.com";
    String subject = "Comformation ";
    String body = "Dear Customer";

    MailMessage msgMail = new MailMessage(sendr, recer, subject, body);

    int PortNumber = 25;
    SmtpClient smtp = new SmtpClient("smtp.test.com", PortNumber);
    msgMail.IsBodyHtml = true;                                     
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
    smtp.Credentials = new System.Net.NetworkCredential(userName, passWord);

    smtp.Send(msgMail);

    MsgLP.Text = "Emailed to Customer..";
    LogInLink.Visible = true;
}
catch (Exception ex){
    AuditLog.LogError("ErrorE-mail " + ex.Message);
}

2 个答案:

答案 0 :(得分:2)

您必须设置smtp.EnableSsl=true并使用端口号587。您的最终代码将是:

try
{
String userName = "ramesh";
String passWord = "123456";
String sendr = "ramesh@gmail.com";
String recer = "customer@yahoo.com";
String subject = "Comformation ";
String body = "Dear Customer";

MailMessage msgMail = new MailMessage(sendr, recer, subject, body);

int PortNumber = 587; //change port number to 587
SmtpClient smtp = new SmtpClient("smtp.gmail.com", PortNumber); //change from test to gmail
smtp.EnableSsl = true; //set EnableSsl to true
msgMail.IsBodyHtml = true;                                     
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential(userName, passWord);
smtp.Send(msgMail);
MsgLP.Text = "Emailed to Customer..";
LogInLink.Visible = true;
}
catch (Exception ex){
AuditLog.LogError("ErrorE-mail " + ex.Message);
}

我使用我的凭据测试了此代码,它运行正常。

答案 1 :(得分:0)

 System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage();
        mm.From = new MailAddress("email@gmail.com");
        mm.To.Add("email@gmail.com");
        System.Net.Mail.Attachment attachment;
        string strFileName;
        strFileName = "Uploadfile/" + "200814062455PM_Admin_Screenshot (10).JPEG";
        attachment = new System.Net.Mail.Attachment(Server.MapPath(strFileName));
        mm.Attachments.Add(attachment);
        mm.Body = ("<html><head><body><table><tr><td>Hi</td></tr></table></body></html><br/>"); ;

        mm.IsBodyHtml = true;
        mm.Subject = "Candidate " + Name + "  for your Requirement " + Jobtt + " ";
        System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
        client.UseDefaultCredentials = false;
        client.Credentials = new System.Net.NetworkCredential("email@gmail.com", "password");
        client.Port = 587;
        client.Host = "smtp.gmail.com";
        client.EnableSsl = true;
        object userstate = mm;
        client.Send(mm);