在C#中发送带附件的邮件

时间:2011-02-27 10:56:09

标签: c# .net email mailmessage

我需要发送一封包含异常详情(黄色死亡屏幕)作为附件的邮件。

我可以按如下方式获得YSOD:

string YSODmarkup = lastErrorWrapper.GetHtmlErrorMessage();
if (!string.IsNullOrEmpty(YSODmarkup))
{
    Attachment YSOD = Attachment.CreateAttachmentFromString(YSODmarkup, "YSOD.htm");
    mm.Attachments.Add(YSOD);
}

mm的类型为MailMessage,但邮件未发送。

下面

System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage("from", "to", "Exception-Details", htmlEmail.ToString());

用于绑定邮件正文。

此后仅添加附件。 删除附件时,会发送邮件。

任何人都可以帮助我吗?


根据Albin先生和Paul先生的意见,我正在更新以下内容

        string YSODmarkup = Ex_Details.GetHtmlErrorMessage();
        string p = System.IO.Directory.GetCurrentDirectory();
        p = p + "\\trial.txt";
        StreamWriter sw = new StreamWriter(p);
        sw.WriteLine(YSODmarkup);
        sw.Close();
        Attachment a = new Attachment(p);       

        if (!string.IsNullOrEmpty(YSODmarkup))
        {
             Attachment  YSOD = Attachment.CreateAttachmentFromString(YSODmarkup, "YSOD.html");
            System.Net.Mail.Attachment(server.mappath("C:\\Documents and Settings\\user\\Desktop\\xml.docx"));

             MyMailMessage.Attachments.Add(a);

        }  

这里我将内容附加到文本文件并尝试相同。所以邮件没有发送。发送包含HTML标签的邮件是否有任何问题。因为我能够附加普通的文本文件。

1 个答案:

答案 0 :(得分:5)

namespace SendAttachmentMail
{
    class Program
    {
        static void Main(string[] args)
        {
            var myAddress = new MailAddress("jhered@yahoo.com","James Peckham");
            MailMessage message = new MailMessage(myAddress, myAddress);
            message.Body = "Hello";
            message.Attachments.Add(new Attachment(@"Test.txt"));
            var client = new YahooMailClient();
            client.Send(message);
        }
    }
    public class YahooMailClient : SmtpClient
    {
        public YahooMailClient()
            : base("smtp.mail.yahoo.com", 25)
        {
            Credentials = new YahooCredentials();
        }
    }
    public class YahooCredentials : ICredentialsByHost
    {
        public NetworkCredential GetCredential(string host, int port, string authenticationType)
        {
            return new NetworkCredential("jhered@yahoo.com", "mypwd");
        }
    }
}