C#使用多行发送Outlook电子邮件
问题描述:
我的代码允许用户键入文本框并使用Outlook将其消息发送给其他用户。该程序工作得很好,除非用户使用多行代码输入东西作为单行打开。C#使用多行发送Outlook电子邮件
例如:
“你好,约翰,
你今天怎么
真诚的,马克?”
将显示为“你好,约翰,你今天好吗真诚? ,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办公室,可以考虑使用一个SMTPClient
到nd电子邮件代替。
按照事实你也不是cleaning up all your COM references在SendMail
,它本身可能是有问题的。
非常感谢!重新格式化HTML已经解决了这个问题。此外,我很欣赏清理我的COM参考的建议。 – Dominick