How to parse email message as html format when there is no attachment - imap

I am new in using IMAP. Now I am trying to use IMAP to see my emails in my web page from mail server. I have configured the settings. And I think the configuration is ok. Now I want to show the message body as html format. My code is:
// getting email body text
if($attachments[1]['is_attachment']!=""){ // if attachmentavailable.
$part_number = '1.2';
}
else{
$part_number = '1';
}
$message = quoted_printable_decode(imap_fetchbody($inbox, $email_number, $part_number));
When email has attachment, it is showing as html format. But when there is no attachment the message is showing as plain text. There is no bold or any other formatted font if I give and there is no link also.
If I use part number 1.2 in else part no message is shown.
Now how can I print email message as html format where there is no attachment.

Learn about the BODYSTRUCTURE format. E-mails can come up in about a ton of different structures, and unless your application actually takes a look at the structure of the MIME message, your code is blindly guessing what to do.

Related

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 send a link via MFMailComposer?

My actual problem is to send a link with a YouTube-Adress per email with Swift.
I use MFMailComposer and sure, it´s no problem to attach a file. But a link?
Is there any way to attach a link only, so the receiver can click the link that calls the YouTube-Page???
Just use HTML for that purpose:
// Add your body in a HTML format
let body = "<p>This is a test. Check out the link to youtube</p> YouTube"
// In your mail instance in setMessageBody, add your body and set isHTML to true
mail.setMessageBody(body, isHTML: true)
Update
If you don´t need a placeholder you could just add http://... URL in the email text as #rmaddy commented.

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.

IMAP - javax.mail. - Fetching Only Body Without Attachment

I am trying to develop an IMAP email client using the javax.mail API. I have been able to contact the servers, fetch emails, attachments and other operations without any problem.
However, we would not want to fetch the attachment until the user wants to view it explit in order to improve the performance. This would mean that we would need information which would indicate if the email has an attachment, if yes, then the filename(s) and the size(s)but would not send me the actual content of the email. However, I was not able to find a method in the API description which would return just the multi-part content.
Is there a way I could fetch just the body and the details of the attachment but not the actual attachment?
Thanks,
Aravind
The method getContent() of javax.Part returns
the content as a Java object. The type
of the returned object is of course
dependent on the content itself. For
example, the object returned for
"text/plain" content is usually a
String object. The object returned for
a "multipart" content is always a
Multipart subclass.
See http://download.oracle.com/javaee/6/api/javax/mail/Part.html#getContent%28%29
If a Message (which is a Part) contains attachments, the getContent method will return a Multipart object. In addition you can know the MIME type of the part with getContentType.
The information that is missing from the documentation is that this MultiPart object returned by getContent is just an empty representation of the Message's structure. The content of each Part of the Multipart will only be fetched from the server when you specifically ask for it. For example, to parse a multipart Message you would do:
if( p.isMimeType("multipart/*") ) {
Multipart mp = (Multipart)p.getContent();
// the content was not fetched from the server
// parse each Part
for (int i = 0; i < mp.getCount(); i++) {
Part inner_part = mp.getBodyPart(i)
if( inner_part.isMimeType("text/plain") ) {
String text = inner_part.getText();
// the content of this Part was fetched from the server
}
}
}
Something else to consider is that for optimal performance you should get the body structure information from the server in batch for the collection of messages you want to parse (see http://download.oracle.com/javaee/6/api/javax/mail/FetchProfile.Item.html#CONTENT_INFO). If not, each
Multipart mp = (Multipart)p.getContent();
will result in a request to the server to fetch the body structure. If the FetchProfile approach is used, the body structure for the collection of messages will be fetched with only one request. You can see the requests to the server in the log if you activate debug mode on the session:
session.setDebug(true);
This said, to get size and filenames of attachments just use Part.getSize() and Part.getFileName(), respectively.

Resources