如何在使用smtp时格式化电子邮件中的文本
本文关键字:电子邮件 格式化 文本 smtp | 更新日期: 2023-09-27 18:19:39
我使用以下方法发送电子邮件。我希望能够用粗体文本格式化电子邮件。
Ex。
发件人:名称
电子邮件:电子邮件地址
消息:消息
我该怎么做?
protected void SendMail()
{
var fromAddress = "myemail@gmail.com";
var toAddress = "myotheremail@gmail.com";
const string fromPassword = "mypassword";
string subject = "New Email from Website";
string body = "From: " + name.Text + "'n";
body += "Email: " + email.Text + "'n";
body += "Message: 'n" + message.Text + "'n";
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body);
}
将isBodyHtml设置为true,下面的代码对其进行了描述,要发送粗体文本,可以使用"<b> My bold text </b>
"。要发送斜体文本,可以使用"<i> Italic text </i>
"。要发送带下划线的文本,可以使用"<u> underlined text </u>
"。
您可以复制并使用以下方法。通过使用这种方法,发送电子邮件将非常容易。
public static bool SendEmail(string To, string ToName, string From, string FromName, string Subject, string Body, bool IsBodyHTML)
{
try
{
MailAddress FromAddr = new MailAddress(From, FromName, System.Text.Encoding.UTF8);
MailAddress ToAddr = new MailAddress(To, ToName, System.Text.Encoding.UTF8);
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 25,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential("your email address", "your password")
};
using (MailMessage message = new MailMessage(FromAddr, ToAddr)
{
Subject = Subject,
Body = Body,
IsBodyHtml = IsBodyHTML,
BodyEncoding = System.Text.Encoding.UTF8,
})
{
smtp.Send(message);
}
return true;
}
catch
{
return false;
}
}
当你调用这个方法时,像这样调用
SendEmail("Here address to" , "Here to name" , "Here from", "here from name", "here subject" , here Body, " Here whether HTML or Plain" )
您只需要进行一些小的更改。
- 假设
IsBodyHtml
是true
- 将所有
'n
替换为<br/>
这是最后的代码
protected void SendMail()
{
var fromAddress = "myemail@gmail.com";
var toAddress = "myotheremail@gmail.com";
const string fromPassword = "mypassword";
string subject = "New Email from Website";
string body = "From: " + name.Text + "<br/>";
body += "Email: " + email.Text + "<br/>";
body += "Message: <br/>" + message.Text + "<br/>";
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body,IsBodyHtml:true);
}
希望能有所帮助。