\ n无法发送电子邮件

时间:2016-05-02 16:55:00

标签: c# asp.net email

我已经制作了一个通过表单发送邮件的代码。这是我的方法:

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("aaaaa@gmail.com");
    mail.From = new MailAddress("aaaaa@gmail.com", "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("aaaa@gmail.com", "password");
    client.Port = 587;
    client.Host = "smtp.gmail.com";
    client.EnableSsl = true;
    try
    {
        client.Send(mail);
        Response.Redirect("sadasd.aspx");
    }
    catch (Exception ex)
    {

    }
}

我的问题是电子邮件很乱,\n无效。如何排队?为什么不起作用?

1 个答案:

答案 0 :(得分: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