1

I know that i'm stuck in a silly problem...and now i am here with hope, that you can help me. Simple situation: I need to send email with attachment from database. I have done it by myself, but...i don't know why, but attachment in email what was send is incorrect. Preciously attachment contents code, what i get from my database.

My code:

static void IncomeMessage()
{
    SqlConnection conn = new SqlConnection("Data Source=xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx");
    SqlCommand cmd = new SqlCommand("Here is my SQL SELECT", conn);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);

    foreach (DataRow dr in dt.Rows)
    {
        try
        {
            var AID = dr["ID"].ToString();
            var Ids = dr["MessageID"].ToString();
            var SuperOrganizationTitle = dr["SuperOrganizationTitle"].ToString();
            var Date = dr["Date"].ToString();
            var Title = dr["Title"].ToString();
            var Description = dr["Description"].ToString();
            var DBFile = dr["File"].ToString();
            var Filename = dr["FileName"].ToString();

            MailMessage oMail = new MailMessage("test@test.com", "guntisvindels@gmail.com", "New message with theme: " + Title, "Message Income: " + Date + " From " + SuperOrganizationTitle + ". Message Content: " + Description);

            DBFile = GetBase64(DBFile);

            var bytes = Encoding.ASCII.GetBytes(DBFile);
            MemoryStream strm = new MemoryStream(bytes);
            Attachment data = new Attachment(strm, Filename);
            ContentDisposition disposition = data.ContentDisposition;
            data.ContentId = Filename;
            data.ContentDisposition.Inline = true;
            oMail.Attachments.Add(data);

            SmtpClient oSmtp = new SmtpClient();
            SmtpClient oServer = new SmtpClient("test.test.com");

            oServer.Send(oMail);
        }
        catch (Exception ex)
        {
            //TraceAdd("Error=" + ex.Message.ToString());
        }
    }
}

For removing unnessessary data ( tags) from database File field i use this code

public static string GetBase64(string str)
{
    var index1 = str.IndexOf("<content>");
    index1 = index1 + "<content>".Length;
    var index2 = str.IndexOf("</content>");
    var kek = Slice(str, index1, index2);
    return kek;
}

public static string Slice(string source, int start, int end)
{
    if (end < 0)
    {
        end = source.Length + end;
    }
    int len = end - start;
    return source.Substring(start, len);
}

When launching my code I can send email to me, and I'll recieve it. But message content attachment with my Base64 code from database File field. Here is a question - Where I got wrong, and how can I recieve email with correct attachment that has been written into database. Thank you for your attention

P.S Attachment in database is written correctly, because K2 integration platform can correctly display it

Here is example what database contain in File column (DBFile)

<file><name>zinojums.html</name><content>PGh0bWw+PGhlYWQ+PG1ldGEgaHR0cC1lcXVpdj0iQ29udGVudC1UeXBlIiBjb250ZW50PSJ0ZXh0L2h0bWw7IGNoYXJzZXQ9dXRmLTgiIC8+PHN0eWxlPmh0bWwsYm9keXtmb250LWZhbWlseTpBcmlhbCxIZWx2ZXRpY2Esc2Fucy1zZXJpZjtmb250LXNpemU6MTBwdDt9aDF7Zm9udC1zaXplOjE0cHQ7fWgye2ZvbnQtc2l6ZToxMnB0O31we2JhY2tncm91bmQtY29sb3I6I0Y3RUVEQTttYXJnaW46MDtwYWRkaW5nOjhweDt9aHJ7aGVpZ2h0OjFweDsgYm9yZGVyOjAgbm9uZTsgY29sb3I6ICM1RjlCRDQ7IGJhY2tncm91bmQtY29sb3I6ICM1RjlCRDQ7fTwvc3R5bGU+PC9oZWFkPjxib2R5PjxoMT5JbmZvcm3EgWNpamEgbm8gVmFsc3RzIGllxYbEk211bXUgZGllbmVzdGE8L2gxPjxoMj5Eb2t1bWVudHMgcGllxYZlbXRzPC9oMj48cD5Ob2Rva8S8dSBtYWtzxIF0xIFqYSBOci4gPGI+TEFUVklKQVMgVkFMU1RTIFJBRElPIFVOIFRFTEVWxKpaSUpBUyBDRU5UUlMgQVMgKDQwMDAzMDExMjAzKTwvYj4gaWVzbmllZ3RhaXMgZG9rdW1lbnRzICI8Yj5aacWGYXMgcGFyIGRhcmJhIMWGxJNtxJNqaWVtPC9iPiIgTnIuIDxiPjU1NDYyNTY5PC9iPiBwaWXFhmVtdHMgdW4gaWVrxLxhdXRzIFZJRCBkYXR1YsSBesSTLjxiciAvPjwvcD48IS0tY29udGVudC0tPjxociAvPsWgaXMgZS1wYXN0cyBpciBpenZlaWRvdHMgYXV0b23EgXRpc2tpLCBsxatkemFtIHV6IHRvIG5lYXRiaWxkxJN0LjxiciAvPlBpZXNsxJNndGllcyBWSUQgRWxla3Ryb25pc2vEgXMgZGVrbGFyxJPFoWFuYXMgc2lzdMSTbWFpOiA8YSBocmVmPSJodHRwczovL2Vkcy52aWQuZ292Lmx2Ij5lZHMudmlkLmdvdi5sdjwvYT4uPC9ib2R5PjwvaHRtbD4=</content></file>
KoalaBear
  • 2,755
  • 2
  • 25
  • 29
  • you make a MemoryStream `strm` from the binary bytes but you never use it. What you attach to the email is the `DBFile` base64 string. Make sure you attach the right thing to your email! – ADyson Aug 06 '18 at 12:40
  • sorry, i add here a little wrong code. I use this - Attachment data = new Attachment(strm, Filename); i change correctly my last working code in question – Guntis Vindels Aug 06 '18 at 12:42
  • Ok then so...in your code, what is the column type of `DBFile` in the database? What does it contain? Give an example perhaps. Your GetBase64() function seems to simply strip some HTML tags from a string...are you sure what you're returning is actually base64 data? – ADyson Aug 06 '18 at 12:45
  • Also I think your method to convert to binary is wrong. See https://stackoverflow.com/a/18827216/5947043 - I think you should be using Convert.FromBase64String . Right now the method you're using takes no account of the fact the string is base64 specifically. – ADyson Aug 06 '18 at 12:47
  • You getting base64 string from xml then attaching it as an attachment. You get what you attach. Do you want to attach decoded content? Have you tried to decode it? – Renatas M. Aug 06 '18 at 12:53
  • I add an example from database File column (DBFile) – Guntis Vindels Aug 06 '18 at 12:54
  • Save the email to a text file. Then open in notepad to make sure the format is correct. – jdweng Aug 06 '18 at 12:55
  • yeah it is html file. I attach also .pdf files, .doc file and .html files – Guntis Vindels Aug 06 '18 at 13:02
  • Thank you!!! You are Gods))) I forget to decode from Base64... problem resolves with string: byte[] frombase64 = Convert.FromBase64String(DBFile); – Guntis Vindels Aug 06 '18 at 13:07
  • This code should use some heavy refactoring. You're not following the [IDisposable]() pattern. You're mixing database logic with email logic. And your string concatenation is hard to read. – mason Aug 06 '18 at 13:29

1 Answers1

5

Right now the method you're using to create binary data from your string takes no account of the fact the string is base64-encoded specifically.

You need to replace

var bytes = Encoding.ASCII.GetBytes(DBFile);

with

var bytes = Convert.FromBase64String(DBFile);
ADyson
  • 57,178
  • 14
  • 51
  • 63