Sending Mails with attachment in C#

13,520
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");
        }
    }
}
Share:
13,520
Anjana
Author by

Anjana

Updated on July 20, 2022

Comments

  • Anjana
    Anjana almost 2 years

    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.

  • JDPeckham
    JDPeckham about 13 years
    oh yea or: message.Attachments.Add(Attachment.CreateAttachmentFromStrin‌​g("MyContent","test.‌​txt"));