What is wrong with my below code. I am trying to place an inline image to an email.
public string SendEmail(SendEmail emailDetails)
{
var x =
"iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAN70lEQVR4Xu3d4XrbyA4D0OT9Hzr3c5u9cZPUc0aFRlKM/VsGBEGCHLvt9vXl5eXtpf+9vL2ZDK+vr0O1FGsINBGQ5CVYE9QuHXrrtk3Gpcsck9ehluFRrDErj0jyEixndu3IGuS9fzrUMjyKlRydJC/BSnI/M1YNUoN8mc8a5EOSGqQGqUEenLAapAapQWqQ8StXPzfI80Oxxqw8IslLsJzZtSN7QXpBekF6QcZbTLe+bFfFGrPyiCQvwXJm146kC3JEw5OySsPPWqNwV620RsmpWMptdZzUeONUg0w+sc7aSOGlQy3Do1jC64gYqbEGuevMWRuujZQh0xolp2IJryNipMYapAb5djZleGqQCwyPbp4rN1y4qw461JJTsZTb6jipsRfkAktAGykDpkMtORVLeB0RIzXWIDVIn1gDd/ZbrH6L9WVEZLv2glxgu+ppvnLDhbvqoEMtORVLua2Okxr7xLrAEtBGyoDpUEtOxRJeR8RIjXGDaNKUINok4aVYKe6/xA/+9d0rYyU11T6KXjXIwRdEmpRs+FmxapCkAhuGOjmIyVKSvK6MldQ0uQR6QTaYLdnMKw91ehBTuqZ5Rb/mlYanhLjhJMVQrCR/0Ut5XRkrqWlSr16QXpBvZ3O12WqQpAIbhjrZ8GQpSV5Xxkpq2gtSg5xi66cHMWWSNK9+BnnvjAqbamR/HySp5AeW9lEubj+D7HSNtPXSTG2kYCkvyan5BEt5SVyaVy/I5AVJNlyaqfkESwbsiMumvCROdVBda5Aa5MvcyfCkB1GGX2LSvGqQGqQGeeC8GqQGqUFqkNw/eiPPD3kK3GLkOaD5BEt5SU7NJ1jKS+LSvHpBekF6QXpBekFk+/4XI1s/valn+D2KTfPqBekF6QXpBekFmdnQvSAfavWCTF6QmUFLxMqwap7k8yOJpfwlLs2rBqlB+sTqEyv3xJItlozpBZlTsxfkTq+kGIo1165/j65B5jT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N4zei2MjapV5K38OoF6QVJzlwvyEhNdeUIR3/9iE0tNR7BSzVbHZfUK8ldeMUvSLKAJJaIoUN9Vl5SY5L7WfXSGpV/9DcKldzqOBkeFSzJPclLsJLcz6qX1qj8a5B3RVUwbYDEyVArL8ESThqjvBRP4pI1Kv8apAaR2fwSowO2CfwvP1SDJNW8wxJhz9pw5SU1JuVVXsmcyRqVfy9IL8imGdYB2wTeC5KUbYwlm+esDVdeUuNYKY9QXo44jkzWqPx7QXpBxpP5TYQO2CbwXpCkbGMs2TxnbbjykhrHSnmE8nLEcWSyRuXfC9ILMp7MXpBNGv2oH9KNIkUnN53kOyJG9RItklhpLeiCpJOeEU+bJNxlKATnzDGql2iRxEprVoPs8MSSoUg3cjVecqiTWGkdapAaZNNMJYc6ibWpmAc/VIPUIJtmKjnUSaxNxdQgY9m0SWOkl5c+sT5UEi1Ue8GS/szE9IL0gszMy/9jk0OdxNpUTC/IWDZt0hipF+ReI9n6qr1gSX9mYnpBekFm5qUXZJNaP+CHdItJqUdsOuGVjFG9RIskVrLGG9b/ALqulR+ih9GsAAAAAElFTkSuQmCC";
var imageData = Convert.FromBase64String(x);
var contentId = Guid.NewGuid().ToString();
var linkedResource = new LinkedResource(new MemoryStream(imageData), "image/jpeg")
{
ContentId = contentId,
TransferEncoding = TransferEncoding.Base64
};
var msg = string.Format("<p><label> Visitor's Name: {0}</lebel></p> " +
"<p><label> Person to Visit: {1} </lebel> </p>" +
"<p><label> Department Name: {2} </lebel> </p>" +
"<p><label> Schedule: {3} </lebel></p>" +
"<div>Present this image to the security guard <br /><img src=\"cid:{4}\" /></div>",
emailDetails.VisitorName, emailDetails.PersonToVisit, emailDetails.DepartmentName,
emailDetails.Schedule, contentId);
string result;
try
{
var htmlView = AlternateView.CreateAlternateViewFromString(msg, null, "text/html");
htmlView.LinkedResources.Add(linkedResource);
var mail = new MailMessage();
var smtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("somename#gmail.com");
mail.To.Add(emailDetails.EmailUsed);
mail.Subject = "Itinerary Gate Pass";
mail.Body = msg;
//mail.IsBodyHtml = true;
smtpServer.Port = 587;
smtpServer.Credentials = new NetworkCredential("somename#sommail.com", "soemthing");
smtpServer.EnableSsl = true;
smtpServer.Send(mail);
result = "Message was sent";
}
catch (Exception )
{
result = "Failed sending Email";
}
return result;
}
If I place a break point in the mail.Body = msg; and copy the value of "msg" in "plnkr", I get the formatted html with the image. Can you show me how to do it please. Thank you.
Email clients will not display base 64 images.
You will either have to display the image by setting the src to an online image accessible over the internet
for example
<img src="http://someurl/someimage.jpg" />
or you would have to attach the image and set the src to
<img src="cid:[The name of the image you attached]" />
So if you say for instance added an attachment named logo.jpg to the email, you will do something like
<img src="cid:logo" />
One important factor you need to consider when following the second approach is that certain email clients will cache images, which might cause problems with incorrect images showing.I would suggest you make use of approach one.
If you do not want to save the file to hard drive, you will need to convert the base 64 string to a byte array which is then used to create an attachment object, for example
var bytes = Convert.FromBase64String(x);
Now you can create the attachment
mail.Attachments.Add(New Attachment(New MemoryStream(bytes),attachmentName))
You have to attach your image in order to reference it with a 'cid':
embedImage = File.ReadAllBytes(imagePath)
mail.Attachments.Add(New Attachment(New MemoryStream(embedImage), imageName))
mail.Attachments(0).ContentId = contentId
Edit: If the only way you can "get" your image is as a Base64 string, try with this... Could work, I guess
embedImage = Convert.FromBase64String(x)
Related
I'm trying to send a mail containing html with inline images as well as a calender invitation (.ics). I have tested that both elements at least work seperately.
If I use Gmail.com to view the mail it displays all elements correctly. Showing information about the event at the top of the mail and showing the text with images. The issue is that depending on the order that I create the alternateViews, it either works with Outlook or Iphone, it always works with gmail.com/gmailclient but not all three at the same time.
SmtpClient sc = new System.Net.Mail.SmtpClient(IP);
MailMessage msg = new MailMessage();
msg.From = new System.Net.Mail.MailAddress("demomail#hotmail.com", "bob");
string mailTo = "client#gmail.com";
msg.To.Add(new MailAddress(mailTo, "Client Name"));
msg.Subject = "Send Calendar Appointment Email";
string mailBody = $"<br><div class=\"dagsordenMødeDato\"> Her er dagsordenen for mødet 10-10-2018 14:45:00 </div><br> <br><ul class=\"dagsordenListe\"><li>Leasing til dig</li><li>Pension</li><li>Garantkunde</li><li>Dine fordele</li></ul><br> <div class=\"bekrivelseAfVedhæftning\">Jeg har vedhæftet et dokument.</div>";
string icsContent = System.IO.File.ReadAllText(#"H:\hjemmelavetICS.ics");
If the alternateView for the calender is placed before the alternateView for Html in the code then it works on 'Mail' for iphone
ContentType contype = new ContentType("text/calendar");
contype.Parameters.Add("method", "REQUEST");
contype.Parameters.Add("name", "Invitation.ics");
contype.CharSet = "utf-8";
AlternateView avCal =
AlternateView.CreateAlternateViewFromString(icsContent, contype);
msg.AlternateViews.Add(avCal);
LinkedResource inlineRådgiver = new LinkedResource(
#"K:\MEDARBEJDERBILLEDER\Signatur Notes\" + "fn" + ".jpg",
MediaTypeNames.Image.Jpeg);
inlineRådgiver.ContentId = "raadgiverID";
inlineRådgiver.ContentType.Name = "Raadgiver.jpg";
LinkedResource inlineKampagne = new LinkedResource(
#"K:\MEDARBEJDERBILLEDER\Signatur Notes\" + "Kampagne" + ".jpg",
MediaTypeNames.Image.Jpeg);
inlineKampagne.ContentId = "kampagneID";
inlineKampagne.ContentType.Name = "Kampagne.jpg";
var htmlContentType =
new System.Net.Mime.ContentType("text/html");
htmlContentType.CharSet = "utf-8";
string embededHtml =
"<img src=cid:raadgiverID alt=\"medarbejder\"></p><img style=\"border: 0;\" src=cid:kampagneID alt=\"kampagne\">";
string fullHtml = mailBody + embededHtml;
var avHtmlBody = AlternateView.CreateAlternateViewFromString(fullHtml, htmlContentType);
avHtmlBody.LinkedResources.Add(inlineRådgiver);
avHtmlBody.LinkedResources.Add(inlineKampagne);
msg.AlternateViews.Add(avHtmlBody);
sc.Send(msg);
However if I add the alternateview for html before the calender then it works for Outlook.
I have been scratching my head over this for a week now, any help would be appreciated.
I am trying to create a facebook share button inside to an email and share the attached video via C#.
First of all, I have attached into the email the video which i am trying to send.
But i can't create via C# the facebook button that i want to share the video.
You may find my source code so far :
public static string logopath = Path.Combine(Application.StartupPath, "logo.png");
public static string videopath = Path.Combine(Application.StartupPath, "test.mp4");
private void button1_Click_1(object sender, EventArgs e)
{
string usermail = textBox1.Text;
bool isUsermailNull = usermail.Equals("");
Console.Out.WriteLine("The variable is " + isUsermailNull);
if (isUsermailNull.Equals(false))
{
try
{
MailAddress m = new MailAddress(usermail);
try
{
MailMessage message = new MailMessage();
SmtpClient smtp = new SmtpClient();
message.From = new MailAddress("myemailaccount#gmail.com");
message.To.Add(new MailAddress(usermail));
message.Subject = "SUBJECT";
message.IsBodyHtml = true;
Attachment inlineLogo = new Attachment(logopath);
Attachment inlineLogo2 = new Attachment(videopath);
message.Attachments.Add(inlineLogo);
message.Attachments.Add(inlineLogo2);
string contentID = "Image";
string contentID2 = "Image2";
inlineLogo.ContentId = contentID;
inlineLogo2.ContentId = contentID2;
//To make the image display as inline and not as attachment
inlineLogo.ContentDisposition.Inline = true;
inlineLogo.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inlineLogo2.ContentDisposition.Inline = true;
inlineLogo2.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
//To embed image in email
//string pass = "123456";
message.Body = "<html><body> <h1 align=\"center\"><img src=\"cid:" + contentID + "\"> </h1><video width=\"400\" controls><source src=\"cid:" + contentID2 + "\" type=\"video/mp4\">Your browser does not support HTML5 video.</video> <h1 align=\"center\">Project</h1> "
+ " <h2 align=\"center\"> NameofProject </h2><h2 align=\"center\">You may find attached your video</h2><div id=\"fb-root\"></div><script>(function(d, s, id) {var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = \"//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.7\"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class=\"fb-video\" data-href=\"cid:" + contentID2 + "\" data-width=\"500\" data-show-text=\"false\"><div class=\"fb-xfbml-parse-ignore\"><blockquote cite=\"cid:" + contentID2 + "\">MyProject </blockquote> </div> </div> <h3 align=\"center\"> Thank you</h3> <h2 align=\"center\">Details</h2> <h2 align=\"center\"> Mail us : myemailaccount#gmail.com</h2> </body></html>";
smtp.Port = 587;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("myemailaccount#gmail.com", "password");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Timeout = 5000000;
smtp.Send(message);
}
catch (Exception ex)
{
MessageBox.Show("err: " + ex.Message);
}
this.Close();
}
catch (FormatException)
{
MessageBox.Show("You haven't put correct email address. Try again!!!!");
}
//Kill all on screen keyboards
Process[] oskProcessArray = Process.GetProcessesByName("TabTip");
foreach (Process onscreenProcess in oskProcessArray)
{
onscreenProcess.Kill();
}
}
else
{
MessageBox.Show("The textbox is null. Please insert an appropriate email address");
}
}
Thank you in advance
You need add in body a hmtl <a> with a url that contains your file like for example:
Share in Facebook
I have some images stored in the Resources.resx file in my solution. I would like to use these images in my email. I have loaded the image into a variable:
Bitmap myImage = new Bitmap(Resources.Image);
and now I want to put it in the HTML in the AlternateView string I am using to create the HTML email. Just need some help.
Here is the HTML string(partial):
body += "</HEAD><BODY><DIV style='height:100%; width:700px;'><div style='height:70px; width:700px; background-color:red;'><img src='" + myImage + "' width='104' height='27' alt='img' style='margin: 20px 0px 0px 20px;'/></div>
Any help would be greatly appreciated Thanks!
EDIT: Here is the entire Code block. I think I am close to getting it, just inexperience getting in the way here :) I tried converting it into a Byte like suggested which got me farther. Still not rendering the image. There is something here I am not doing right. Thank you so much for all of you help everyone! Here is the code (the HTML I need for the image is in the 3 line of the string body = code):
if (emailTo != null)
{
Bitmap myImage = new Bitmap(Resources.comcastHeader);
ImageConverter ic = new ImageConverter();
Byte[] ba = (Byte[])ic.ConvertTo(myImage, typeof(Byte[]));
MemoryStream image1 = new MemoryStream(ba);
LinkedResource headerImage = new LinkedResource(image1, "image/jpeg");
headerImage.ContentId = "companyLogo";
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("" + emailTo + "");
message.Subject = "" + customer + " Your order is being processed...";
message.From = new System.Net.Mail.MailAddress("noreply#stormcopper.com");
string body = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
body += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">";
body += "</HEAD><BODY><DIV style='height:100%; width:700px;'><div style='height:70px; width:700px; background-color:red;'><img src=\"cid:companyLogo\" width='104' height='27' alt='img' style='margin: 20px 0px 0px 20px;'/></div><P>Hello " + customer + ",</P><P>Thank you for shopping at <a href='" + store + "'>" + store + "</A>. Your order is being processed and will be shipped to you soon. We would like to take this time to thank you for choosing Storm Copper Components, and we hope you are completely satisfied with your purchase. Please review your information and make sure all the information is correct. If there are any errors in your order, please contact us immediately <A href='mailto:busbar#stormcopper.com'>here.</A></P>";
body += "<P><B>Here is your order information:</B></P>";
body += "<H3>Contact Information</H3><TABLE><TR><TD><B>Name:</B> " + customer + "</TR></TD><TR><TD><B>Address:</B> " + street + " " + city + ", " + state + " " + zip + "</TR></TD><TR><TD><B>Email:</B> " + emailTo + "</TR></TD><TR><TD><B>Phone:</B> " + phone + "</TR></TD><TR><TD></TD></TR></TABLE>";
body += "<H3>Products Ordered</H3><TABLE>" + productInformation + "</TABLE><BR /><BR />";
body += "<H3>Pricing Information</H3><TABLE><TR><TD>Subtotal: $" + subTotal + "</TD></TR><TR><TD>Shipping: $" + shippingInfo + " </TD></TR><TR><TD>Tax: $" + taxInfo + "</TD></TR><TR><TD><B>Total:</B> $" + total + "</TD></TR><BR /></TABLE>";
body += "<P>Thank you for shopping with us!</P><A href='stormcopper.com'>Storm Copper Components</A>";
body += "<P><I>This is an Auto-Generated email sent by store copper. Your email will not be sent to Storm Copper Components if you reply to this message. If you need to change any information, or have any questions about your order, please contact us using the information provided in this email.</I></P></DIV></BODY></HTML>";
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
message.AlternateViews.Add(alternate);
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("########");
smtp.Send(message);
}
you need to add them in the email message as CID's/linked resources.
here is some code I have used before which works nicely. I hope this gives you some guidance:
Create an AlternateView:
AlternateView av = AlternateView.CreateAlternateViewFromString(body, null, isHTML ? System.Net.Mime.MediaTypeNames.Text.Html : System.Net.Mime.MediaTypeNames.Text.Plain)
Create a Linked Resource:
LinkedResource logo = new LinkedResource("SomeRandomValue", System.Net.Mime.MediaTypeNames.Image.Jpeg);
logo.ContentId = currentLinkedResource.Key;
logo.ContentType = new System.Net.Mime.ContentType("image/jpg");
// add it to the alternative view
av.LinkedResources.Add(logo);
// finally, add the alternative view to the message:
msg.AlternateView.Add(av);
here is some documentation to help you with what the AlternativeView and LinkedResources are and how it works:
http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/system.net.mail.linkedresource(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/ms144669(v=vs.110).aspx
in the HTML itself, you need to do something like the following:
"<img style=\"width: 157px; height: 60px;\" alt=\"blah blah\" title=\"my title here\" src=\"cid:{0}\" />";
notice the CID followed by a string format {0} - I then use this to replace it with a random value.
UPDATE
To go back and comment on the posters comments... here is the working solution for the poster:
string body = "blah blah blah... body goes here with the image tag: <img src=\"cid:companyLogo\" width="104" height="27" />";
byte[] reader = File.ReadAllBytes("E:\\TestImage.jpg");
MemoryStream image1 = new MemoryStream(reader);
AlternateView av = AlternateView.CreateAlternateViewFromString(body, null, System.Net.Mime.MediaTypeNames.Text.Html);
LinkedResource headerImage = new LinkedResource(image1, System.Net.Mime.MediaTypeNames.Image.Jpeg);
headerImage.ContentId = "companyLogo";
headerImage.ContentType = new ContentType("image/jpg");
av.LinkedResources.Add(headerImage);
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.AlternateViews.Add(av);
message.To.Add(emailTo);
message.Subject = " Your order is being processed...";
message.From = new System.Net.Mail.MailAddress("xxx#example.com");
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
message.AlternateViews.Add(alternate);
// then send message!
One option is put the image in one host, and in the src put the url, like this "src='http://www.host/myImage.jpg'"
This way you do not have to load the image in each mail and would be more agile.
If it helps anyone, here is a version based on Ahmed ilyas' very useful answer, which passes the actual Bitmap to the memory stream, and encloses the various objects which implement IDisposable in using blocks -
public void SendMailExample(string emailAddressTo, string hexColour)
{
// Give the LinkedResource an ID which should be passed into the 'cid' of the <img> tag -
var linkedResourceId = "mylogo";
var sb = new StringBuilder("");
sb.Append("<body><p>This is the HTML email body with img tag...<br /><br />");
sb.Append($"<img src=\"cid:{linkedResourceId}\" width=\"100\" height=\"115.5\" alt=\"Logo\"/>");
sb.Append("<p></body>");
var emailBodyHtml = sb.ToString();
var emailBodyPlain = "This is the plain text email body";
using (var message = new MailMessage())
using (var logoMemStream = new MemoryStream())
using (var altViewHtml = AlternateView.CreateAlternateViewFromString(emailBodyHtml, null, System.Net.Mime.MediaTypeNames.Text.Html))
using (var altViewPlainText = AlternateView.CreateAlternateViewFromString(emailBodyPlain, null, System.Net.Mime.MediaTypeNames.Text.Plain))
using (var client = new System.Net.Mail.SmtpClient(_smtpServer)
{
Port = 25,
DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
EnableSsl = false
})
{
message.To.Add(emailAddressTo);
message.From = new MailAddress(_emailAddressFrom);
message.Subject = "This is the email subject";
// Assume that GetLogo() just returns a Bitmap (for my particular problem I had to return a logo in a specified colour, hence the hexColour parameter!)
Bitmap logoBitmap = GetLogo(hexColour);
logoBitmap.Save(logoMemStream, System.Drawing.Imaging.ImageFormat.Png);
logoMemStream.Position = 0;
using (LinkedResource logoLinkedResource = new LinkedResource(logoMemStream))
{
logoLinkedResource.ContentId = linkedResourceId;
logoLinkedResource.ContentType = new ContentType("image/png");
altViewHtml.LinkedResources.Add(logoLinkedResource);
message.AlternateViews.Add(altViewHtml);
message.AlternateViews.Add(altViewPlainText);
client.Send(message);
}
}
}
I know this is an old post, but if someone still hits this looking for an answer (like I did), then I have a simpler answer.
You can use a simple overload of LinkedResource object that directly takes the file path as the parameter. So there is no need to explicitly load image into memory stream. Of course, this example assumes you have access to the image on the disk -
Here is the complete function code which worked for me -
public System.Net.Mail.AlternateView GetAlternateView(string MessageText, string LogoPath, bool bSilent)
{
try
{
MessageText += "<br><img title='' alt='' src='cid:SystemEmail_HTMLLogoPath' />";
System.Net.Mail.AlternateView view = System.Net.Mail.AlternateView.CreateAlternateViewFromString(MessageText, null, "text/html");
System.Net.Mail.LinkedResource linked = new System.Net.Mail.LinkedResource(HttpContext.Current.Request.PhysicalApplicationPath + LogoPath);
linked.ContentId = "SystemEmail_HTMLLogoPath";
view.LinkedResources.Add(linked);
return view;
}
catch (Exception ex)
{
if (bSilent)
return null;
else
throw ex;
}
}
you should not assign the Bitmap object to <img> tag as it expects the image path.
Replace this:
body += "</HEAD><BODY><DIV style='height:100%; width:700px;'><div style='height:70px; width:700px; background-color:red;'><img src='" + myImage + "' width='104' height='27' alt='img' style='margin: 20px 0px 0px 20px;'/></div>
With following :
body += "</HEAD><BODY><DIV style='height:100%; width:700px;'><div style='height:70px; width:700px; background-color:red;'><img src='" + Resources.Image+ "' width='104' height='27' alt='img' style='margin: 20px 0px 0px 20px;'/></div>
I use outlook Redemption dll for creating outlook message template with c# language.
Below is my code:
RedemptionLoader.DllLocation64Bit = Server.MapPath("~/bin/dlls/Redemption64.dll");
RedemptionLoader.DllLocation32Bit = Server.MapPath("~/bin/dlls/Redemption.dll");
Interop.Redemption.RDOSession session = RedemptionLoader.new_RDOSession();
var msg = session.GetMessageFromMsgFile(templatePath);
msg.Subject = String.Format("Report");
String ImageString = Server.MapPath("~\\FolderName") + "\\" + ImageName;
RDOAttachment Attach = msg.Attachments.Add(ImageString);
Attach.ContentID = "image1";
String htb = "<html><head><title>The Title</title></head><body><h1>This is some text</h1>Image 1<br /><img src=cid:image1><br /></body></html>";
msg.HTMLBody = htb;
msg.Save();
msg.SaveAs(newPath);
Everything work and image is saved to new location. But when i check that message template, i could not see Image anywhere. instead of image it gives me error.
Update
Instead of embedded image , I tried just to attach this file. But when I open file I didn't see any attachment. I check Total Attachments with OutlookSpy, It shows me 0 attachment. Does my code wrong for attachment?
I found solution for this. I need to call session two time. First time to save attachment to my template file and than again to create new instance of it. Below is my code:
RedemptionLoader.DllLocation64Bit = Server.MapPath("~/bin/dlls/Redemption64.dll");
RedemptionLoader.DllLocation32Bit = Server.MapPath("~/bin/dlls/Redemption.dll");
Interop.Redemption.RDOSession session1 = RedemptionLoader.new_RDOSession();
var msg1 = session1.GetMessageFromMsgFile(templatePath);
msg1.Subject = String.Format("Report");
String ImageString = Server.MapPath("~\\FolderName") + "\\" + ImageName;
RDOAttachment Attach = msg1.Attachments.Add(ImageString);
Attach.ContentID = "image1";
String htb = "<html><head><title>The Title</title></head><body><h1>This is some text</h1>Image 1<br /><img src=cid:image1><br /></body></html>";
msg1.HTMLBody = htb;
msg1.Save();
Interop.Redemption.RDOSession session = RedemptionLoader.new_RDOSession();
var msg = session.GetMessageFromMsgFile(templatePath);
msg.SaveAs(newPath);
This works for me.
I want to send a file via email using c# ASP.net (Maybe more files too, but for the moment I'm concerned about sending at least only one file)
For the moment, I do have a method that does work if you want to send an Email
public string EnviarMensaje(int intIdVendedor, string strCorreoPara, string strCorreosAdicionales, string strTema, string strMensaje, string strRuta)
{
string strResultado="";
DataTable dt = ConexionBD.GetInstanciaConexionBD().GetVendedorEspecifico(intIdVendedor);
string strCuerpo = strMensaje + "\n\n\n\nMensaje Enviado Por:\n" + dt.Rows[0]["Vendedor"] + "\n" + dt.Rows[0]["Email"] + "\n" + dt.Rows[0]["Telefono"];
string[] strListaCorreos = strCorreosAdicionales.Split(new Char[] {' ', ','}, StringSplitOptions.RemoveEmptyEntries);
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtpout.secureserver.net");
mail.Subject = strTema;
mail.Body = strCuerpo;
mail.From = new MailAddress(strCorreoDe);
mail.To.Add(strCorreoPara);
foreach (string c in strListaCorreos)
{
mail.To.Add(c);
}
if (strRuta != "")
{
Attachment attachment;
attachment = new Attachment(strRuta);
mail.Attachments.Add(attachment);
}
SmtpServer.Port = 80;
SmtpServer.Credentials = new System.Net.NetworkCredential(strCorreoDe, strContrasena);
SmtpServer.EnableSsl = false;
SmtpServer.Send(mail);
strResultado = "Exito";
}
catch (Exception ex)
{
strResultado = ex.ToString();
}
return strResultado;
}
in aspx I have
<asp:FileUpload ID="fileUploadArchivos" runat="server" />
<asp:ImageButton ID="imgBtnEnviar" runat="server" Height="60px" Width="60px" ImageUrl="~/img/iconos/email.png" CausesValidation = "True" ValidationGroup="vgpCorreo" onclick="imgBtnEnviar_Click" />
and on the cs I have
EnviarEmail objEmail = new EnviarEmail();
protected void imgBtnEnviar_Click(object sender, ImageClickEventArgs e)
{
if (fileUploadArchivos.HasFile)
{
strArchivo = Path.GetTempFileName();\\RIGHT NOW I LEFT IT THIS WAY, BUT I NOW THAT HERE IS THE PROBLEM, I DON'T KNOW WHTAT CAN I DO HERE
}
string strResultado = objEmail.EnviarMensaje((int)Session["IdVendedor"], lblCorreoPara.Text, tbxCorreoPara.Text, tbxTema.Text, tbxMensaje.Text, strArchivo);
}
However, the problem is in a FileUpload.
I have tried many methods like, Server.MapPath, Path.GetFileName, GetDirectoryName, GetFullPath, GetPathRoot... and I'm always getting either nothing, only the filename or a completely different path (I guess is a server kind of path)..
I only for the moment want to get a file path as simple as C:\Test.txt for example...
I suppose that if I can get that exact string from the FileUpload, I'll be able to send it... However, I can't figure out how to make it work.
Hope you can help me
Thanks
If you need a local copy of the file uploaded kept on the server you can just do
fuFileUpload.SaveAs(MapPath(filepath));
Then your strRuta can use the file you just saved via
strRuta = Server.MapPath(filepath);
ready to pass into the new Attachment object.
You don't need to save the file at all to disk, not if all you want to do with it is add it as an attachment.
FileUpload has a FileContent property that is a Stream - some of the constructors of the Attachment class take a stream as a parameter.
The solution is to pass this stream to your method and use it directly.
In code behind:
string strResultado = objEmail.EnviarMensaje((int)Session["IdVendedor"],
lblCorreoPara.Text,
tbxCorreoPara.Text,
tbxTema.Text,
tbxMensaje.Text,
fileUploadArchivos.FileContent);
In your class:
public string EnviarMensaje(int intIdVendedor,
string strCorreoPara,
string strCorreosAdicionales,
string strTema,
string strMensaje,
Stream attachmentData)
{
...
var attachment = new Attachment(attachmentData, "nameOfAttachment");
...
}
You can try with this, using a stream instead of a simple text:
public string EnviarMensaje(int intIdVendedor, string strCorreoPara, string strCorreosAdicionales, string strTema, string strMensaje, string strRuta)
{
string strResultado="";
DataTable dt = ConexionBD.GetInstanciaConexionBD().GetVendedorEspecifico(intIdVendedor);
string strCuerpo = strMensaje + "\n\n\n\nMensaje Enviado Por:\n" + dt.Rows[0]["Vendedor"] + "\n" + dt.Rows[0]["Email"] + "\n" + dt.Rows[0]["Telefono"];
string[] strListaCorreos = strCorreosAdicionales.Split(new Char[] {' ', ','}, StringSplitOptions.RemoveEmptyEntries);
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtpout.secureserver.net");
mail.Subject = strTema;
mail.Body = strCuerpo;
mail.From = new MailAddress(strCorreoDe);
mail.To.Add(strCorreoPara);
foreach (string c in strListaCorreos)
{
mail.To.Add(c);
}
bool hasAttachment = !string.IsNullOrWhitespace(strRuta);
System.IO.FileStream stream = null;
Attachment attachment = null;
if (hasAttachment)
{
// Create a file stream.
stream = new FileStream(strRuta, FileMode.Open, FileAccess.Read);
// Define content type.
ContentType contentType = new ContentType();
contentType.MediaType = MediaTypeNames.Text.Plain; // or whatever your attachment is
// Create the attachment and add it.
attachment = new Attachment(stream, contentType);
mail.Attachments.Add(attachment);
}
SmtpServer.Port = 80;
SmtpServer.Credentials = new System.Net.NetworkCredential(strCorreoDe, strContrasena);
SmtpServer.EnableSsl = false;
SmtpServer.Send(mail);
strResultado = "Exito";
// Don't forget to release the resources if the attachment has been added
if (hasAttachment)
{
data.Dispose();
stream.Close();
stream.Dispose();
}
}
catch (Exception ex)
{
strResultado = ex.ToString();
}
return strResultado;
}