I want to send mails with images in them. The code I've written works fine, but for some reason unknown to me it wont work with Outlook clients.
The test mail I sent was (left: Thunderbird, right: Outlook):
What my code is supposed to do is: It takes the RTF from a RichTextBox and converts it to HTML. This leaves the images embedded in the HTML as base64 strings. I extract all base64 encoded images one by one and put them into a MemoryStream which is accepted by LinkedResource. Since mail clients usually don't accept embedded images I replace the embedded image in the HTML with a content-id. Then I set some properties of LinkedResource and add it to an AlternateView. This alternate view is then added to a System.Net.Mail.MailMessage and the mail is sent.
The corresponding code:
MemoryStream mem = null;
private readonly Regex embeddedImageRegex = new Regex("src=\"data:image/.*?\"");
public MyHTMLMailMessage()
: base()
{
this.SubjectEncoding = Encoding.UTF8;
this.BodyEncoding = Encoding.UTF8;
this.IsBodyHtml = true;
}
public bool Send()
{
// create HTML View with images
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(HTML, System.Text.Encoding.UTF8, MediaTypeNames.Text.Html);
ReplaceEmbeddedImagesWithCID(htmlView);
this.AlternateViews.Add(htmlView);
this.Body = HTML;
SmtpClient client = new SmtpClient(server, port);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = String.IsNullOrEmpty(username);
try
{
client.Send(this);
return true;
}
catch (SmtpException e)
{
return false;
}
finally
{
mem?.Close();
}
}
private void ReplaceEmbeddedImagesWithCID(AlternateView altView)
{
string extension;
int imageIndex = 0;
string contentID = $"image{imageIndex}";
// go through every base64 string, create a content id and LinkedResource for it
while (embeddedImageRegex.IsMatch(HTML))
{
extension = new Regex("image/.*?;").Match(HTML).Value
.Replace("image/", "")
.Replace(";", "");
string base64img = embeddedImageRegex.Match(HTML).Value
.Replace("src=\"", "")
.Replace("\"", "")
.Split(',')[1];
HTML = embeddedImageRegex.Replace(HTML, $"src=\"cid:image{imageIndex}\"", 1);
byte[] byBitmap = Convert.FromBase64String(base64img);
mem = new MemoryStream(byBitmap);
mem.Position = 0;
LinkedResource linkedImage = new LinkedResource(mem, $"image/{extension}");
linkedImage.ContentId = contentID;
altView.LinkedResources.Add(linkedImage);
altView = AlternateView.CreateAlternateViewFromString(HTML, null, MediaTypeNames.Text.Html);
imageIndex++;
}
}
So I went through different solutions but none of them worked.
My steps so far:
I edited some registration keys in HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\x.0\Outlook\Options\Mail or HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\x.0\Common
I left the image as base64 string in the HTML
There were some properties added
linkedImage.TransferEncoding = TransferEncoding.Base64;
linkedImage.ContentType.Name = contentID;
linkedImage.ContentLink = new Uri($"cid:{contentID}");
this.Headers.Add("Content-ID", $"<image{imageIndex}>");
this.Headers.Add("X-Attachment-Id", $"image{imageIndex}");
altView.TransferEncoding = TransferEncoding.QuotedPrintable;
None of this worked for me even although it seemed to help others. Did i overlook something?
Base64 images are blocked by default in Outlook.
You need to attach images to the email and set the PR_ATTACH_CONTENT_ID property on the email (the DASL name is "http://schemas.microsoft.com/mapi/proptag/0x3712001E"). See Embed Images in New Messages using a Macro for more information.
Have you confirmed it is not an image block from Trust Center Settings.
Unblock image downloads for a single message:
Click the InfoBar at the top of the message.
Click Download Pictures.
Unblock image downloads for all messages:
Outlook 2007
On the "Tools" menu, click Trust Center > Automatic Download.
Uncheck the "Don't download pictures automatically in HTML e-mail messages or RSS items" check box.
Outlook 2010 and Up:
On the "File" tab, click Options > Trust Center.
Under Microsoft Outlook Trust Center, click Trust Center Settings.
Uncheck the "Don't download pictures automatically in HTML e-mail messages or RSS items" check box.
Unblock picture downloads for all messages from a particular email address or domain:
In an open message that was sent from a particular email address or domain, right-click on a blocked item.
Do one of the following:
Click Add Sender to Safe Senders List.
Click Add the Domain [#domain] to Safe Senders List.
Related
I want to send a (view page) pdf sending by email.but when I trying to add an attachment, I found an error below "Add". for that I can't successfully sending mail with attaching my view pdf.
Here is my code:
(Ordercontroller)
//other code
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Test Project", "pt300#gmail.com"));
message.To.Add(new MailboxAddress("psm", "p689#gmail.com"));
message.Subject = "Hi,this is demo email";
message.Body = new TextPart("plain")
{
Text = "Hello,My First Demo Mail it is.Thanks",
};
//add attach
var aa = new ViewAsPdf("Cart")
{
FileName = "Invoice.pdf", //actually, I don't know why this filename is
// "Invoice". I found this system on a website.
PageOrientation = Rotativa.AspNetCore.Options.Orientation.Portrait,
};
message.Attachments.Add(aa);
//end attach
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587, false);
client.Authenticate("pt300#gmail.com", "MyPassword");
client.Send(message);
client.Disconnect(true);
}
//other code
and these controller's view I trying to pdf and send by mail:
(HomeController)
public ActionResult Cart()
{
List<Product> products = HttpContext.Session.Get<List<Product>>("products");
if (products == null)
{
products = new List<Product>();
}
return View(products);
}
in OrderController I found an error.
how I will solve this problem and successfully send my view's pdf by mail.please help.
Attachments is a MimeMessage property that has no such method Add, so here comes the error. To add the attachments you should create a BodyBuilder object before, with this class you will be able to add new attachments (each one of them as byte array), usign Attachments Property and its Add method, but always related to BodyBuilder, not to MimeMessage.
Please, take a look to the answer given here, as I guess is what you are looking for:
.net Core Mailkit send attachement from array
Or check another example here:
https://www.taithienbo.com/send-email-with-attachments-using-mailkit-for-net-core/
In addition, you could get Rotativa PDF as byte array usign this code:
var rotativaAction = new ViewAsPdf("Cart")
{
FileName = "Invoice.pdf", // You can change this file name to set whatever you want
PageOrientation = Rotativa.AspNetCore.Options.Orientation.Portrait,
};
byte[] fileAttachmetByteArray = rotativaAction.BuildFile(ControllerContext);
Once you have generated your PDF as a byte array using Rotativa, guessing you have stored the result in a variable called fileAttachmentByteArray (as stated in the previous code sample), you must simply send this variable (the byte array) to the Add method of the BodyBuilder, as the second parameter (first is the attachement file name, which is completely free to use the name you prefer), and then set Mime Message Body, usign the BodyBuilder you have worked with.
So, to explain the process in steps:
On the first line you create a BodyBuilder variable, and initialize it, using the text you want as body for the email.
Then, you call Add method to add a new attachment, sending to it the file name you wish and your previously created bye array
Finally, you asign the value to the Body property of your Mime Message
And your code should look like this:
var builder = new BodyBuilder { HtmlBody = "yourBodyMessage" }; // Change "yourBodyMessage" to the email body you desire
builder.Attachments.Add("filename", fileAttachmentByteArray); // Once again, you can change this "filename" to set whatever you want
mimeMessage.Body = builder.ToMessageBody(); // Assuming mimeMessage is the same variable you provided in your code
I've had some success encoding the RTFbody from a MailItem using UTF8Encoding. I'm able to compose a new email, do all the new-email stuff and click send. Upon hitting send, I append the email with a tag that is also added to the categories. This all works and all through the RTFBbody.
The problem comes when I reply to RTF emails, which, for testing purposes, are just the emails I sent to my lonesome self. When I send the reply email and new tags were added, I remove the old tags first and then add the new tags. When I set the RTFBody in the reply email with the edited string that contains the new tags, I get a "not enough memory or disk space" error. This doesn't happen when I just remove the tags with the same function.
Bellow is the code I'm using:
private void ChangeRTFBody(string replaceThis, string replaceWith)
{
byte[] rtfBytes = Globals.ThisAddIn.email.RTFBody as byte[];
System.Text.Encoding encoding = new System.Text.UTF8Encoding();
string rtfString = encoding.GetString(rtfBytes);
rtfString = rtfString.Replace(replaceThis, replaceWith);
rtfBytes = encoding.GetBytes(rtfString);
Globals.ThisAddIn.email.RTFBody = rtfBytes; < // The error is here only on
// reply and only when I replace
// with new tags
}
These are the calls I make:
Delete old tag: ChangeRTFBody(lastTag, "");
Add new tag: ChangeRTFBody("}}\0", newTag + "}}\0");
Like I said, This works when I create a new email and send it, but not when I try to reply to the same email. It also seems that the size of the byte[] almost doubles after the delete. When I check it during the Delete it's at about 15k bytes and when I check during the Add it jumps to over 30k bytes. When I try to add the newly inflated byte[] to the rtfBody is when I get the error.
Thanks for any help and tips and sorry about all the reading.
I had the same problem and came across what I think is an easier way to replace text in a outlook rtf body by using the Word.Document object model. You will need to add reference of Microsoft.Office.Interop.Word to your project first.
then add using
using Word = Microsoft.Office.Interop.Word;
then your code would look like
Word.Document doc = Inspector.WordEditor as Word.Document;
//body text
string text = doc.Content.Text;
//find text location
int textLocation = text.IndexOf(replaceThis);
if(textLocation > -1){
//get range
int textLocationEnd = textLocation + replaceThis.Length;
//init range
Word.Range myRange = doc.Range(textLocation , textLocationEnd);
//replace text
myRange.Text = replaceWith
}
I have created an application at work that generates exel files from some database data. After generating the files they are sent automatically to the customers in question. My problem is that it works fine when i run the published application. But some users when they run the application the files are generated perfectly as they are saved on the HDD and i can see them. But when they are attached to the MailMessage object they get corrupted. This is an image of the corrupted files. These files should be Excel files.
This is my code for sending a mail with attached files:
public void SendMailedFilesDK()
{
string[] sentFiles = Directory.GetFiles(sentFilesDK);
if (sentFiles.Count() > 0)
{
using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("ares"))
{
using (System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage())
{
msg.From = new MailAddress("system#mail.dk");
msg.To.Add(new MailAddress("operation#mail.dk"));
msg.To.Add(new MailAddress("bl#mail.dk"));
msg.CC.Add("lmy#mail.dk");
msg.CC.Add("ltr#mail.dk");
msg.Subject = "IBM PUDO";
msg.Body = sentFiles.Count() + " attached file(s) has been sent to the customer(s) in question ";
msg.IsBodyHtml = true;
foreach (string file in sentFiles)
{
Attachment attachment = new Attachment(file);
msg.Attachments.Add(attachment);
}
client.Send(msg);
}
}
}
}
Why are the files getting corrupted when others run the application? We are all using office 2010.
You should make sure to set the content type of the attachement to the appropriate value.
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet for xlsx files, or
application/vnd.ms-excel for xls files.
For example, your loop should look something like this.
ContentType xlsxContent = new ContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
foreach (string file in sentFiles)
{
Attachment attachment = new Attachment(file, xlsxContent);
msg.Attachments.Add(attachment);
}
We use this in our Attachment constructor and have no issues attaching Excel and PDF.
Attachment data = new Attachment(sFileName, MediaTypeNames.Application.Octet);
Also check that the users running this have permissions to access the files in whatever location is specified by sentFilesDK.
You might want to specify the mimetype which is part of one of the constructors on Attachment class.
public Attachment(string fileName, ContentType contentType);
You can also read the file in memorystream and pass it as part of the following constructor.
public Attachment(Stream contentStream, string name, string mediaType);
I have recently started using C# over the past year so I'm somewhat new to this, but can usually hack through things with some effort, but this one is eluding me. We use TestTrack for development bug/issue tracking at our company. I've created a custom windows forms app to be the front-end to TestTrack for one of our departments. It connects using SOAP. I'm not using WPF/WCF and don't want to go that route. I'm having difficulty finding any examples of how to correctly encode a file for attachment that is a PDF. The code below does actually create an attachment in TestTrack to an already-existing issue, but when you try to open it in TestTrack, it pops up an error message that says "Insufficient Data For An Image". The example below does work if you're wanting to add a text file to TestTrack using SOAP. I'm wanting to know what I need to change below so that I can get a PDF file into TestTrack and then be able to open it in the TestTrack application without the error mentioned above. Thanks in advance for any input/help.
public void getAttachments(long lSession, CDefect def)
{
ttsoapcgi cgiengine = new ttsoapcgi();
// Lock the defect for edit.
CDefect lockedDefect = cgiengine.editDefect(lSession, def.recordid, "", false);
string attachment = "c:\\TEST\\TEST_PDF.PDF";
CFileAttachment file = new CFileAttachment();
file.mstrFileName = Path.GetFileName(attachment);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
StreamReader reader = new StreamReader(attachment);
file.mstrFileName = Path.GetFileName(attachment);
file.mpFileData = enc.GetBytes(reader.ReadToEnd());
reader.Close();
CReportedByRecord reprec = lockedDefect.reportedbylist[0];
CFileAttachment[] afile = reprec.attachmentlist;
if (afile == null)
{
lockedDefect.reportedbylist[0].attachmentlist = new CFileAttachment[1];
lockedDefect.reportedbylist[0].attachmentlist[0] = file;
}
// Save our changes.
cgiengine.saveDefect(lSession, lockedDefect);
}
}
Here is the modified method that allowed me to attach a PDF to SOAP and get it into TestTrack as an attachment to an issue:
public void getAttachments(long lSession, CDefect def)
{
ttsoapcgi cgiengine = new ttsoapcgi();
// Lock the defect for edit.
CDefect lockedDefect = cgiengine.editDefect(lSession, def.recordid, "", false);
string attachment = "c:\\TEST\\TEST_PDF.PDF";
CFileAttachment file = new CFileAttachment();
file.mpFileData = File.ReadAllBytes(attachment);
file.mstrFileName = Path.GetFileName(attachment);
CReportedByRecord reprec = lockedDefect.reportedbylist[0];
CFileAttachment[] afile = reprec.attachmentlist;
if (afile == null)
{
lockedDefect.reportedbylist[0].attachmentlist = new CFileAttachment[1];
lockedDefect.reportedbylist[0].attachmentlist[0] = file;
}
// Save our changes.
cgiengine.saveDefect(lSession, lockedDefect);
}
I want to dynamically create an email and send it. So far so good, the problem is that it's in dutch language and it doesn't display correctly.
I am doing this:
// Body Html
if (!string.IsNullOrEmpty(emailMessage.BodyHtml))
{
var encoding = Encoding.UTF32;
byte[] byteArray = Encoding.GetEncoding("iso-8859-1").GetBytes(emailMessage.BodyHtml);
byte[] unicodeArray = Encoding.Convert(Encoding.GetEncoding("iso-8859-1"), encoding, byteArray);
emailMessage.BodyHtml = encoding.GetString(unicodeArray);
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType();
ct.MediaType = MediaTypeNames.Text.Html;
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(emailMessage.BodyHtml, ct);
mailMessage.AlternateViews.Add(htmlView);
htmlView.TransferEncoding = TransferEncoding.QuotedPrintable;
}
try
{
smtpSender.Send(mailMessage);
}
The mail should contain Financiƫle details but when i open the mail with outlook i see Financiele details
How to fix it?
Please have a look at the InternetCodepage property of the Outlook mailitem. I had a similar issue with a new e-Mail in which I inserted text from an existiing e-mail, in which German Umlauts didn't displaying correctly. This was solved after I set the InternetCodepage in the new e-mail to the appropriate value of the original e-mail.
See http://msdn.microsoft.com/en-us/library/office/ff860730.aspx for more information about this property and a list of possible values.