电子邮件修改

时间:2019-01-10 06:49:16

标签: c#

我正在将Visual Studio 2015用于Windows应用程序窗体。我从一个基本程序开始,该程序通过电子邮件以表格形式发送信息。电子邮件功能运行良好,但我无法使它在电子邮件中显示为可读。我的目标是在不同的行中显示每个标签和文本框。即: 批号:1111 件数:2 说明:xyz ...等

     private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

            mail.From = new MailAddress("myemail");
            mail.To.Add("sendingTo");
            mail.Subject = "subject";  
            mail.Body = toName.Text lot.Text;


            SmtpServer.Port = 587; 
            SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
            SmtpServer.EnableSsl = true;

            SmtpServer.Send(mail);
            MessageBox.Show("Sent");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

我的问题在-mail.Body。如何创建包含文本和变量的新行,这些新行会很好地出现在电子邮件中。

谢谢!

3 个答案:

答案 0 :(得分:0)

您是说要创建新行吗?您可以通过将\n放在任何字符串中来实现。

要将变量添加到字符串中,只需使用+字符即可,例如:

bar = foooo
barr = baaaaar
foo = bar + barr

您将得到:

foooobaaaaar

答案 1 :(得分:0)

尝试将两个“ \ r \ n”都移到下一行。

例如

mail.Body = toName.Text + "\r\n" + lot.Text + "\r\n" + pieces.Text + "\r\n" + description.Text;

"Name: ABC \r\n Lot number: 1111 \r\n Pieces: 2 \r\n Description: xyz\r\n"

答案 2 :(得分:0)

理想的解决方案是使用 https://www.stringtemplate.org/ [https://github.com/antlr/stringtemplate4]

您可以具有带有变量的HTML模板。然后,使用上述库将您的实际值填充到模板中。

我们正在项目中有效使用这些工具。

还请注意:System.Net.Mail SmtpClient现在已过时。 下面是来自MS Documents:

https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient?view=netframework-4.7.2

改用MailKit https://github.com/jstedfast/MailKit

希望这会有所帮助。

干杯!