我的代码允许用户在文本框中键入内容,然后使用 Outlook 将他们的消息发送给另一个用户。该程序运行良好,除非用户键入多行内容,它在 Outlook 中作为单行打开。
例如:
“你好约翰,
你今天好吗?
真诚的,马克“
将显示为“Hello John,How are you today? Sincerely, Mark”
我如何才能以正确的间距发送这些消息?
我的文本框的代码是:
<asp:TextBox ID="txtMessage" runat="server" placeholder="Please Enter Your Message Here." rows="18" style="width:100%; margin-top:20px; margin-bottom:20px" TextMode="MultiLine" MaxLength="9999" />
我的电子邮件功能的代码是:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace Cards
{
public partial class _Message : _Default
{
//Declaring global variables for the email function to be used in this class.
protected string toEmail, emailSubj, emailMsg;
protected void Page_Load(object sender, EventArgs e)
{
if (lblName.Text == null) return;
lblUserId.Text = Session["userid"].ToString();
lblName.Text = Session["name"].ToString();
lblBirth.Text = Session["birth"].ToString();
lblEmail.Text = Session["email"].ToString();
lblHire.Text = Session["hire"].ToString();
}
protected void btnSend_Click(object sender, EventArgs e)
{
//Calling the parts to construct the email being sent
toEmail = lblEmail.Text;
emailSubj = "It's Your Special Day";
emailMsg = txtMessage.Text;
SendMail(toEmail, emailSubj, emailMsg);
MessageBox.Show("Successfully sent message to " + lblName.Text, "Message Sent!", MessageBoxButtons.OK, MessageBoxIcon.Information);
Response.Redirect("~/Default.aspx");
}
private static void SendMail(string toEmail, string subj, string message)
{
//This class will call all parts to the email functionality and generate the constructors for the email messsage.
try
{
// Create the Outlook application.
Outlook.Application oApp = new Outlook.Application();
// Create a new mail item.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
//Add the body of the email
oMsg.HTMLBody = message;
//Subject line
oMsg.Subject = subj;
// Add a recipient.
Outlook.Recipients oRecips = oMsg.Recipients;
// Change the recipient in the next line if necessary.
Outlook.Recipient oRecip = oRecips.Add(toEmail);
oRecip.Resolve();
// Send.
oMsg.Send();
}
catch (Exception ex)
{
MessageBox.Show("An error has occurred. Please report this error to the Development team",
"Error found!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
最佳答案
您发送的是 HTML,新行没有意义。
以纯文本形式发送:
oMsg.Body = message;
格式为 HTML:
oMsg.HTMLBody = message.Replace("\r\n", "<br />");
不推荐从 ASP.Net 自动化 Office,考虑使用 SMTPClient
改为发送电子邮件。
就目前情况而言,您也不是cleaning up all your COM references在SendMail
,这本身就有问题。
关于C# 使用多行发送 Outlook 电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35656787/