[英]How do I send formatted text in email using C#?
以下是我發送電子郵件的代碼段:
MySqlCommand cmdsd;
MySqlConnection conn;
string s23 = "";
conn = new MySqlConnection("server=localhost;database=projecttt;uid=root;password=techsoft");
conn.Open();
//smtp which will be loaded is webmail.techsofttechnologies.com
cmdsd = new MySqlCommand("select smtp from smtp", conn);
MySqlDataReader dr45 = cmdsd.ExecuteReader();
while (dr45.Read())
{
s23 = dr45.GetString(0).Trim();
}
string s1 = textBox3.Text;
string s4 = textBox1.Text;
string S5 = textBox2.Text;
string attachment = textBox5.Text;
MailMessage mail = new MailMessage();
mail.From = new MailAddress(s4, S5);
mail.BodyEncoding = Encoding.UTF8;
mail.To.Add(s1);
mail.Subject = textBox4.Text;
mail.Body = "<body>"+textBox6.Text+"</body>";
//mail.Body = textBox6.AppendText("\n");
AlternateView planview = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable tby those clients that don't support html");
AlternateView htmlview = AlternateView.CreateAlternateViewFromString("<b>This is bold text and viewable by those mail clients that support html<b>");
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
System.Net.Mail.Attachment jil = new System.Net.Mail.Attachment(attachment);
mail.Attachments.Add(jil);
SmtpClient smtp = new SmtpClient(s23);
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
Exception exc = ex;
string Message = string.Empty;
while (exc != null)
{
Message += exc.ToString();
exc = exc.InnerException;
}
}
conn.Close();
this.Close();
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
郵件正文包含帶換行符的文本。
但是我無法格式化文本。 在郵件中,它顯示為連續的行,並用空格代替換行符。
如何使它按預期工作?
您可能需要將換行符轉換為正確的HTML換行符:
text.Replace("\n", "<br/>")
對於電子郵件的HTML版本,您將需要用<br />
標記替換換行符。 一個簡單的string.Replace
。 string.Replace
應該做到這一點。
對於純文本電子郵件,我想您的電子郵件已按照需要進行格式化,並且您正在使用Outlook接收電子郵件。
Outlook有助於刪除它認為是額外的空格(通常是任何空格)的內容。 有一個選項可以將其關閉,通常在完全打開郵件時會在窗口頂部顯示該選項。
要將其完全關閉以用於Outlook:
工具 > 選項 > 首選項 > 電子郵件選項 ...>取消選中在純文本消息中刪除多余的換行符
大家好,
感謝您提供的所有幫助。
我在以下鏈接中得到了答案
基本上,替換功能將給出答案。
完整的答案如下:
//The text will be loaded here
string s2= textBox6.Text;
//All blank spaces would be replaced for html subsitute of blank space( )
s2 = s2.Replace(" ", " ");
//Carriage return & newline replaced to <br/>
s2=s2.Replace("\r\n", "<br/>");
string Str = "<html>";
Str += "<head>";
Str += "<title></title>";
Str += "</head>";
Str += "<body>";
Str += "<table border=0 width=95% cellpadding=0 cellspacing=0>";
Str += "<tr>";
Str += "<td>" + s2 + "</td>";
Str += "</tr>";
Str += "</table>";
Str += "</body>";
Str += "</html>";
mail.Subject = textBox4.Text;
mail.Body = Str;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.