Im trying to send an email via HTTP Client in c# by sending a html string and i wish to send with the image that is inside the html body but the mail sends the html raw code and send 2 .dat attachments
I try to use alternative view and linked resource to send the image
My Email Method is this:
try
{
SmtpClient client = new SmtpClient();
{
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential()
{
UserName = "mailaccount@gmail.com",
Password = "mypaswrd"
};
};
MailAddress fromEmail = new MailAddress("mailaccount@gmail.com", "Name");
MailAddress toEmail = new MailAddress("mailaccount@gmail.com", "Name");
AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlString, null, "image/jpg");
LinkedResource linkedResource = new LinkedResource(@"routeofmyimage");
alternateView.ContentId = "logo";
alternateView.LinkedResources.Add(linkedResource);
MailMessage message = new MailMessage()
{
From = fromEmail,
Subject = "Subject",
IsBodyHtml = true,
Body = htmlString,
};
if (alternateView != null)
{
message.AlternateViews.Add(alternateView);
}
message.To.Add(toEmail);
try
{
client.Send(message);
}
catch (Exception ex)
{
}
}
catch (Exception ex)
{
}
My CreateHTMLBody Method
public static string getHtmlTruckData(/*string IDTruck, DataTable data*/)
{
try
{
string messageBody = "";
string styleFormat = "<style>" +
"table.border {" +
"border-collapse:collapse;" +
"}" +
"table-border th {" +
"padding: 5px; " +
"border: 1px solid black" +
"}" +
"table.border td {" +
"padding: 5px; " +
"border: 1px solid black" +
"}" +
"</style>";
string htmlMainTableStart = "<table style=\"width:100%;\">";
string htmlMainTableEnd = "</table>";
string headerHTMLFormat = "<tr>" +
"<td style=\"width:20%;\">" +
"<td style=\"width:60%\" align=\"center\">" +
"<table>" +
"<img src=\"cid:logo\"/>"+
"</table>" +
"</td>" +
"<td style=\"width:20%;\">" +
"<table class=\"border\" style=\"width:100%\">" +
"<tr><td align=\"center\">"+ DateTime.Now.ToShortDateString() + "</td> </tr>" +
"<tr><td align=\"center\">" + "Daily Trip Report" + "</td> </tr>" +
"</table>"+
"</td>" +
"</td>" +
"</tr>";
messageBody = styleFormat;
messageBody += htmlMainTableStart;
messageBody += headerHTMLFormat;
messageBody += htmlMainTableEnd;
return messageBody;
}
catch (Exception ex)
{
return null;
}
}
The Sent Mail:
<style>table.border {border-collapse:collapse;}table-border th {padding: 5px; border: 1px solid black}table.border td {padding: 5px; border: 1px solid black}</style><table style="width:100%;"><tr><td style="width:20%;"><td style="width:60%" align="center"><table><img src="cid:logo"/></table></td><td style="width:20%;"><table class="border" style="width:100%"><tr><td align="center">10/7/2022</td> </tr><tr><td align="center">Daily Trip Report</td> </tr></table></td></td></tr></table>