Sending Mails with attachment in C#

Anjana picture Anjana · Feb 27, 2011 · Viewed 13.3k times · Source

I need to send a mail including the exception details (Yellow Screen Of Death) as attachment.

I could get the YSOD as follows:

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.

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. Because i was able to attach a normal text file.

Answer

JDPeckham picture JDPeckham · Feb 27, 2011
namespace SendAttachmentMail
{
    class Program
    {
        static void Main(string[] args)
        {
            var myAddress = new MailAddress("[email protected]","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("[email protected]", "mypwd");
        }
    }
}