Embed Documents using LinkedResources for MailMessage - attachment

I'm using the following code to embed images into my MailMessage. What I'm trying to do is embed documents (pdf or docx) into the email.
I've tried hyperlink with a link to href="cdi:myDoc.pdf" but that doesn't work. I've also tried using MailMessage.Attachments.Add() but adds the documents in the attachments section instead of embeding the document in the message.
Anyone how to embed a document in the mailmessage? I know Outlook is able to place the attachments in the body of the message but I can't figure how to do it through mailMessage.
Thanks Susan
Sub MultiPartMime()
Dim mail As New MailMessage()
mail.From = New MailAddress("me#mycompany.com")
mail.To.Add("you#yourcompany.com")
mail.Subject = "This is an email"
Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString("<b>this is bold text, and viewable by <img src=""cdi:companylogo""> those mail clients that support html</b>", Nothing, "text/html")
LinkedResource logo = new LinkedResource( "c:\temp\logo.gif" )
logo.ContentId = "companylogo"
htmlView.LinkedResources.Add(logo)
mail.AlternateViews.Add(htmlView)
'send the message
Dim smtp As New SmtpClient("127.0.0.1") 'specify the mail server address
smtp.Send(mail)
End Sub 'MultiPartMime

Try using cid: instead of cdi:. That is one error that comes to mind.

try to use
href="cid:companylogo
(with "cid" instead of "cdi" Like Jakob Mygind suggested) and set it to the contentId that you specified for the LinkedResource.
Also when setting the path to the file, it is good to use the HostingEnvironment.MapPath() method (which is the same of Url.Content() of web projects. It would go with something something like:
LinkedResource logo = new LinkedResource(HostingEnvironment.MapPath("c:\temp\logo.gif"));
Hope it helps!
;)

Related

Image is not shown in email MVC

I have a strange problem.
I need to send an e-mail from an MVC site. I have an html template for the email, which looks like this(the image part):
...
<img class="auto-style4" src="{PictureSrc}" /><br />
<img src="data:image/png;base64,{pictureBase64}">
....
From the controller I'm replacing the parameters like this:
case "PictureSrc":
string imagePath = "";
imagePath = "~/Images/email-logo.png";
//string base64 = Convert.ToBase64String(System.IO.File.ReadAllBytes(HttpContext.Server.MapPath(imagePath)));
//content = content.Replace("{pictureBase64}", base64);
content = content.Replace("{" + property + "}", HttpContext.Server.MapPath(imagePath));
break;
1.First I have tried to add the path for the image. This way works on my local machine, but not on the server where the live site is.
I've tried to add the URL for the image. WhenI have pasted the URL in to the browser, the image was shown, but in the sent email the image was not shown, not in my local machine, not on the server.
The interesting thing is that I'm sending these mails to outlook accounts. There the images are not shown, but if I send the mail to my yahoo account there the image is shown.
I've tried to convert image to base 64, as you can see on the code and replacing this way the image src. This way again the image was not shown, not on my local machine, not on the server side if I send the mail to outlook accounts. If I send the mail to a yahoo account, the mail is shown.
Can you please advise what can I try in order to resolve this problem?
I ran into this same issue with Outlook a few months ago. While researching, I learned that Outlook tends to strip emails of embedded images. I resolved it by using the CID technique. This technique consists of attaching the image to the email and referencing it in the email template with the image's CID.
First, you would need to get your image's CID. There are plenty of CID converters online to do this. Then, you just need to use the CID in the img src attribute of your template: <img src="cid:" + yourCID + "/>".
Note: this WILL increase the size of your email due to the image being attached.

how to create a zendesk ticket with inline image

I would like to create a ticket with inline image but cannot get through it. I am using a rich text having a pasted screen capture image, the content is like
"<img ..."
By using ZendeskApi_V2, I set the Ticket's Comment HtmlBody with the content mentioned but did not work, neither of PlainBody or Body.
Anyone can help, please.
For instance:
In my application, an image is inserted into a RadEditor
By setting the Ticket.Comment as
var ticket = new Ticket {
Comment = new Comment {
HtmlBody = HttpUtility.HtmlDecode(RadEditor.Content)
}
}
After sending the Create Ticket request, I cannot see the inline image in the Zendesk dashboard.
So, did I do it in a right way? How should an embedded or inline image be sent through Zendesk API?
You may need to upload the attachment file first, then you can set the attachment's token in the comment. See here - https://developer.zendesk.com/rest_api/docs/support/tickets#attaching-files

Create inline image that displays properly in iOS mail app

So I have tried 2 different approaches to creating an inline image using c#:
Using an AlternateView
Using an inline Attachement
Option 2 is worse in that it does not appear inline on any of my test clients (outlook 2010/2013, Samsung android email client, ios 10 email client).
Option 1 is almost perfect, all clients display the inline image correctly as long as there are no other attachments. However, if you add a file attachment to the email, only on the iOS email app you get a strange side effect. On iOS, the client displays both the inline image and the attachment as attachments (the inline image is shown as an icon).
I have tried to figure this out by composing an email in Outlook with an embedded image and an attachment. Outlook generates what looks to be two regular attachments (looking at the raw message data from both Outlook and dotNet generated emails), with the image being marked as content-disposition inline. And this works on all my test clients. Except when using the .Net Mail message api to replicate this (option 2), it doesn't work. I am at a loss to understand what is going on here.
Edit 1
What's interesting is that when using Option 2, the email body is delivered encoded as base64. This is different than how the Outlook client manages to do it. There the body is in plain text and the inline attachment image is the only thing encoded in bas64.
Edit 2
Setting the following properties when using Option 2 returns the body to being plain text again:
mail.BodyEncoding = Encoding.UTF8;
mail.BodyTransferEncoding = TransferEncoding.QuotedPrintable;
So to get this to work I had to combine both approaches. Below is what worked for me, it displays the signature image as intended (inline/embedded) image and the attachment as an icon (in iOS anyway). This also displayed correctly on a Samsung Android phone and in outlook 2010/2013. For the sake of simplicity, I will only include the embedded image in the mail body as an example:
var smtpMail = new SmtpClient
using (var mail = new MailMessage())
{
mail.From = new MailAddress(Settings.Default.FromAddress, Settings.Default.FromDisplayName);
mail.To.Add(toAddress);
mail.Subject = subjectText;
mail.IsBodyHtml = true;
mail.BodyEncoding = Encoding.UTF8;
mail.BodyTransferEncoding = TransferEncoding.QuotedPrintable;
mail.Attachments.Add(new Attachment(nonInlinefilePath));
var imgCid = "img001.jpg"
var bodyText = $"<html><body><img src=\"cid:{imgCid}\" alt=\"Sample Image\" /></body></html>";
var altView = AlternateView.CreateAlternateViewFromString(bodyText, Encoding.UTF8, MediaTypeNames.Text.Html);
var inlineFileResource = new LinkedResource(imagePath, MediaTypeNames.Image.Jpeg)
{
TransferEncoding = TransferEncoding.Base64,
ContentId = imgCid,
ContentType =
{
Name = imgCid
},
};
var inlineFileAttachment = new Attachment(imagePath, MediaTypeNames.Image.Jpeg)
{
ContentId = imgCid
};
inlineFileAttachment.ContentDisposition.Inline = true;
inlineFileAttachment.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
altView.LinkedResources.Add(inlineFileResource);
mail.AlternateViews.Add(altView);
mail.Attachments.Add(inlineFileAttachment);
smtpMail.Send(mail);
}
I don't know enough about either email protocols or the iOS email app to know why this is necessary, but after many, many, many different attempts to get iOS mail app to display this properly, this combo was the only one that worked.
I had a similar issue with a work project. Images embedded in the message body using System.Net.Mail LinkedResource, would appear fine in most email clients, but not with iOS emails after a version upgrade during version 10.
The images would have zero bytes and added attachments with zero size. What I did was to fix this was to define the media type, whereas before I didn't.
Before:
LinkedResource logo = new LinkedResource(HttpContext.Current.Server.MapPath("/images/imgname.png"));
After:
LinkedResource(HttpContext.Current.Server.MapPath("/images/imgname.png"), "image/png");
as a possible alternative you could try base64 encoding your image.
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADSCAMAAABThmYtAAAAXVB" alt="img" />
I just tested my image in Outlook, outlook for web, and iOS Mail. worked in all for me.
you could use this tool (or any base64 encoder) to generate a base64 image tag
more info here.
another good source of info on this subject

How to fetch mail by id with barbushin imap class

I'm currently working on the imap class by barbushin. It's the only php class over the internet I can find regardless to any encoding issue. Thanks to the coder.
I have a list of messages in a table. Each message sending a message id as GET (say $mid). When a link clicked, the page turned into a view page. It should open that message and display the relevant content right? But it is not. Every message has the same content (the 1st content). The code is designed for gmail but I use it for my client. And it's work.
This is a code:
require_once('../ImapMailbox.php');
define('EMAIL', 'my#domain.com');
define('PASSWORD', '*********');
define('ATTACHMENTS_DIR', dirname(__FILE__) . '/attachments');
$mailbox = new ImapMailbox('{imap.gmail.com:993/imap/ssl}INBOX', EMAIL, PASSWORD, ATTACHMENTS_DIR, 'utf-8');
$mails = array();
// Get some mail
$mailsIds = $mailbox->searchMailBox('ALL');
if(!$mailsIds) {
die('Mailbox is empty');
}
$mailId = reset($mailsIds);
$mail = $mailbox->getMail($mailId);
var_dump($mail);
var_dump($mail->getAttachments());
The original is here: https://github.com/barbushin/php-imap
Finally, I found my way home. According to the script there's a line says "mailId". Which is straight forward what is it about.
It was set to the first array by reset(). So the only thing I need to do is extract the message id from it ($mailId is an array of ids). So I simply add an array behind it.
$mailId=$mailsIds[$_GET[uid]];
While $_GET[uid] is a message id sent from a previous page.

Problem attaching file programmatically to blackberry Email Client

I am attempting to attach an excel spreadsheet to an email programmatically, and then launch the default blackberry email client with the message as an argument. Unfortunately, I receive the error: "Email service does not support these types of attachments. Change the Send Using field or remove the attachments." The send button is not present, and there is no "Send" option in the menu; this is blocking the ability to send the email.
This error occurs when I load the package onto my physical blackberry phone, as well as in the simulator.
I am able to send the email without a hitch if I use the API instead (the commented transport.send line).
Any and all input would be greatly appreciated, and if I've overlooked some details please let me know.
public Email()
{
try{
message = new Message();
multipart = new Multipart(); //Multi part can hold attachment AND body (and more)
subject = "Service Change Request";
multipart.addBodyPart( new TextBodyPart( multipart, "Hi XXXXXX, \n Here are the details for CLIENT" ) );
byte[] data = null;
InputStream stream = MyAPP.getUiApplication().getClass().getResourceAsStream("/blank_form.xls");
data = IOUtilities.streamToBytes(stream);
stream.close();
multipart.addBodyPart( new SupportedAttachmentPart( multipart, "application/octet-stream", "ServiceUpdate.xls", data ) );
Address recipients[] = new Address[1];
recipients[0]= new Address("*******#gmail.com", "user");
message.setSubject(subject);
message.setContent( multipart );
message.addRecipients(Message.RecipientType.TO, recipients);
//Transport.send(message);
}catch(Exception e){
}
}
public void send(){
Invoke.invokeApplication( Invoke.APP_TYPE_MESSAGES, new MessageArguments( message ) );
}
EDIT:
The error comes up because the simulator has no email account configured. It should work just fine on any phone that has an email account properly configured.
I hope this helps and I am not too late to lend a hand on this post.
I've worked with attachments before, and they are a pain to work with in Blckberry.
The only issue I can think of is the MIME type you are trying to use.
"Application/octet-stream", try using the MIME corresponding to the extension of the attachment, for example "application/excel" for .xls files. You can find the complete list here , its the longest one I could find.
There are also some issues with the Blackberry email service and attachments that are mentioned on several Knowledge Base Articles on the official Developers page like this one, they sometimes say that the attachments have to be prefixed with "x-rimdevice" in the file name, like "x-rimdevice-serviceupdate.xls". Although I'm not really sure this affects on outgoing email, but I thought it was worth mentioning.
By the way, I'm trying to use your code for an App I'm coding right now, so I'm kind of hoping it works.

Resources