简体   繁体   English

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

[英]Sending Mails with attachment in C#

I need to send a mail including the exception details (Yellow Screen Of Death) as attachment. 我需要发送一封邮件,包括例外情况(黄色死亡屏幕)作为附件。

I could get the YSOD as follows: 我可以得到YSOD如下:

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

mm is of type MailMessage , but the mail is not sent. mm的类型为MailMessage ,但不发送邮件。

Here 这里

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

is used to bind the body of the mail. 用于绑定邮件正文。

After this only the attachment is added. 在此之后,仅添加附件。 While removing the attachment, mail is sent. 删除附件时,会发送邮件。

Can anyone help me out? 谁能帮我吗?


As per the comments from Mr. Albin and Mr. Paul am updating the following 根据阿尔宾先生和保罗先生的评论,我正在更新以下内容

        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);

        }  

Here i attached the contents to a text file and tried the same. 在这里,我将内容附加到文本文件并尝试相同。 So the mail was not sent. 所以邮件没有发送。 Is there any issue with sending mails which contains HTML tags in it. 发送包含HTML标签的邮件是否有任何问题。 Because i was able to attach a normal text file. 因为我能够附加普通的文本文件。

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");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM