2016-05-02 47 views
-1

我製作了一個通過表單發送郵件的代碼。這是我的方法: n在發送郵件時不工作

protected void SendMail() 
{ 

    string firstName = fName.Text.ToString(); 
    string lastName = lName.Text.ToString(); 
    string event = eventName.Text.ToString(); 
    string phoneNum = phone.Text.ToString(); 
    string pass1 = pass.Text.ToString(); 
    string address1=address.Text.ToString(); 
    string email = gmail.Text.ToString(); 
    string body = "From: " + firstName+" " +lastName+ "\n"; 
    string subject = "title " + event; 
    body += "Email: " + email + "\n"; 
    body += "Event: " + event + "\n"; 
    body += "Phone Number: " + phoneNum + "\n"; 
    body += "Password: " + pass1 + "\n"; 
    body += "Event address: " + address1 + "\n"; 
    // smtp settings 
    System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(); 
    mail.To.Add("[email protected]"); 
    mail.From = new MailAddress("[email protected]", "title", System.Text.Encoding.UTF8); 
    mail.Subject = "title"; 
    mail.SubjectEncoding = System.Text.Encoding.UTF8; 
    mail.Body = body; 
    mail.BodyEncoding = System.Text.Encoding.UTF8; 
    mail.IsBodyHtml = true; 
    mail.Priority = System.Net.Mail.MailPriority.High; 
    SmtpClient client = new SmtpClient(); 
    client.Credentials = new System.Net.NetworkCredential("[email protected]", "password"); 
    client.Port = 587; 
    client.Host = "smtp.gmail.com"; 
    client.EnableSsl = true; 
    try 
    { 
     client.Send(mail); 
     Response.Redirect("sadasd.aspx"); 
    } 
    catch (Exception ex) 
    { 

    } 
} 

我的問題是,電子郵件是一個很大的混亂和\n不工作。我怎樣才能得到一條線?爲什麼它不工作?

+2

您可以使用'Environmen.NewLine'而不是'\ n'。因爲新行字符取決於操作系統。' –

+1

用'+ Environment.NewLine()替代'\ n';' – MethodMan

+2

消息正文爲html。嘗試使用
Marusyk

回答

3

我這個"\n"應替換爲"<br />"。和StringBuilder將更適合構建MailMessage,代碼將如下所示:

StringBuilder mailBodyBuilder = new StringBuilder(); 
mailBodyBuilder.Append("From: " + firstName +" " + lastName + "<br />"); 
mailBodyBuilder.Append("Email: " + email + "<br />"); 
mailBodyBuilder.Append("Event: " + event + "<br />"); 
mailBodyBuilder.Append("Phone Number: " + phoneNum + "<br />"); 
mailBodyBuilder.Append("Password: " + pass1 + "<br />"); 
mailBodyBuilder.Append("Event address: " + address1 + "<br />"); 
// rest of contents here 
// send the mail