While trying to read a multipart/signed mail, the original attachments are ignored and only smime.7ps file is displayed - jakarta-mail

I am trying to connect to a mailbox and read the messages and attachments. Here when there is any mail with a digital signature, only the smime.7ps file is read and others(xml,pdf etc.,) are ignored. I could observe that in such mails only the signature part of mail is read and body part is ignored. I am using Multipart here. Please let me know if there is any different way of handling which could help me to get the body part attachments read for mails with Digital Signature? Here is the part of my code which fetches the messages/attachments:
if (contentType.contains("multipart")){
Multipart multiPart = (Multipart) message.getContent();
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
// this part is attachment
String fileName = part.getFileName();
attachFiles += fileName + ", ";
part.saveFile(SaveDirectory + File.separator + fileName);
} else {
// this part may be the message content
messageContent = part.getContent().toString();
}
}
if (attachFiles.length() > 1) {
attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
}
//}
} else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
Object content = message.getContent();
if (content != null) {
messageContent = content.toString();
}
}

Thanks Shannon! Your input of nested multiparts actually helped me to solve the issue!
MimeMultipart multiPart = (MimeMultipart) message.getContent(); //* Reading the Email Message & its contents*
//***Your code for Different actions with Email Message
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
//***Reading Body Part contents from the Email Message
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
//***Your Code for Different actions with Body part contents
//***Now the below step would help you to check if the above retrieved content(part) is having any further multiparts nested in it.
//***Once the check is true, then you can instantiate that content again as a multipart and retrieve the related details.
if(part.getContent() instanceof Multipart){
Multipart multipart = (Multipart) part.getContent();
for (int j = 0; j < multipart.getCount(); j++) {
MimeBodyPart bodyPart = (MimeBodyPart)multipart.getBodyPart(j);
}
}
}

Related

arrayoutofboundsexception when using flickr api

i have a piece of code thats makes a image search on flickr and returns the URL of the first image with that name. certain words i search on flickr doesn't have any matching images so because there are no images to get i get an ArrayOutOfBoundsException [0]. is there a way that i can make the program skip that particular words and keep on searching with next words?
this is my code so far:
PImage[] images;
int imageIndex;
XML xml;
String tag = "rutte";
String tag_mode = "all";
String words[];
void setup() {
size(50, 50);
String lines[] = loadStrings("text.txt");
words = split(lines[0], " ");
for (int k = 0; k<words.length; k++) {
String query = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=MY API KEY&tags="+ words[k] + "&sort=relevance&tag_mode="+ tag_mode +"format=rest";
xml = loadXML(query);
XML[] children = xml.getChildren("photos");
if(children.length > 0){
XML[] childPhoto = children[0].getChildren("photo");
for (int i = 0; i < 1; i++) {
String id = childPhoto[i].getString("id"); // this line generates the error :(
String title = childPhoto[i].getString("title");
String user = childPhoto[i].getString("owner");
String url = "https://www.flickr.com/photos/"+user+"/"+id;
println(url);
println("=====================");
}
}
}
textAlign(CENTER, CENTER);
smooth();
}
void draw() {
}
Just use the length field of your array. Something like this:
XML[] children = xml.getChildren("photos");
if(children.length > 0){
XML[] childPhoto = children[0].getChildren("photo");
if(childPhoto.length > 0){
String id = childPhoto[0].getString("id");
//rest of your code
}
You can find more info in the Processing reference.
In fact, you're already doing this with your words array!

How to Read a Text file Using Actionscript 3?

I am trying to read a text file in my air project. It is actually the config file used by TinkerProxy. I have the following so far:
//Read settings from TinkerProxy Config File
var TextFileLoader:URLLoader = new URLLoader();
var ArrayOfLines:Array;
TextFileLoader.addEventListener(Event.COMPLETE, onLoaded);
TextFileLoader.load(new URLRequest("/tinkerproxy-2_0/serproxy.cfg"));
//TextFileLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
function onLoaded(e:Event):void {
ArrayOfLines = e.target.data.split(/\r/);
trace(e.target.data);
}
trace(ArrayOfLines[0]);
What I'm really trying to do is find the 'net_port1=5331' entry and store '5331' in a variable.
Here is a sample of the text file:
# Generated by TinkerProxy Configurator
#
# Timeout in seconds
# 0 means infinite, no timeout
timeout=0
newlines_to_nils=false
comm_ports=1
serial_device1=COM1
net_port1=5331
comm_baud1=9600
comm_databits1=8
comm_stopbits1=1
comm_parity1=none
The file is autogenerated so I can not edit it (or rather I'd want to read it as it is generated.)
I'm able to see the data via trace(e.target.data) but I cannot access the data via trace(ArrayOfLines[0]); for instance.
What am I missing?
Thanks in advance.
You probably need to split on \n (Unix) or \r\n (Windows), not \r.
Usually when loading a text file from the filesystem and breaking into lines, I normalize line endings by doing this:
var lines:Array = text.replace(/\r\n/g, "\n").split("\n");
Then you can iterate over the lines and decode each line as desired. The file appears to be akin to .properties format, for which there is no built in parser in AS3 (like XML, JSON, or URLVariables) but it's a pretty simple format. For example, this:
var props:Object = {};
for each(var line:String in lines){
// skip blank lines and comment lines
if(line == "" || line.charAt(0) == "#")
continue;
var arr:Array = line.split("=");
if(arr.length == 2)
props[arr[0]] = arr[1];
}
trace(JSON.stringify(props, null, 2))
Outputs this:
{
"comm_parity1": "none",
"comm_ports": "1 ",
"newlines_to_nils": "false",
"comm_baud1": "9600",
"serial_device1": "COM1",
"comm_databits1": "8",
"timeout": "0",
"comm_stopbits1": "1",
"net_port1": "5331"
}
Which allows you to access properties by name:
trace(props.net_port1); // "5331"
(Note that all values are strings, so for example newlines_to_nils is not false, it is "false".)
Alternatively, you could search for the key you are looking for and extract just the data you want:
var key:String = "net_port1=";
var index:int = text.indexOf(key);
if(index != -1){
// extract text after the desired search key
var value:String = text.substring(index + key.length);
// parseInt will read until it hits a non-numeric character
var net_port1:int = parseInt(value);
trace(net_port1); // 5331
}
Here is the solution that worked for me. Thanks again to Aaron for his answer on properties. I may use that in the future.
//Read settings from TinkerProxy Config File
var TextFileLoader:URLLoader = new URLLoader();
var ArrayOfLines:Array;
var Port:int;
var COM:int;
TextFileLoader.addEventListener(Event.COMPLETE, onLoaded);
TextFileLoader.load(new URLRequest("/tinkerproxy-2_0/serproxy.cfg"));
function findSubstring(array:Array, string:String):int {
for(var i:int = 0; i < array.length; i++){
if(array[i].indexOf(string) > -1){
return i; //Index of Substring
}
}
return -1; //Not Found
}
function onLoaded(e:Event):void {
ArrayOfLines = e.target.data.split(String.fromCharCode(13));
if(findSubstring(ArrayOfLines, "net_port") > -1){
Port = Number(ArrayOfLines[findSubstring(ArrayOfLines, "net_port")].split("=")[1]);
}
else{
Port = 5331; //Default if not port is found.
}
if(findSubstring(ArrayOfLines, "serial_device1") > -1){
COM = Number(ArrayOfLines[findSubstring(ArrayOfLines, "serial_device1")].split("serial_device1=COM")[1]);
}
else{
COM = 1; //Default if not port is found.
}
trace("COM: " + COM + " Port: " + Port);
}

Reading and parsing text file exception-C#

I am parsing big text files and it's working fine for some time but after few minutes it give me exception (An unhandled exception of type 'System.UnauthorizedAccessException' occurred in System.Core.dll
Additional information: Access to the path is denied.)
I get exception on below mention line.
accessor = MemoryMapped.CreateViewAccessor(offset, length, MemoryMappedFileAccess.Read);
Below is my function
public static void CityStateZipAndZip4(string FilePath,long offset,long length,string spName)
{
try
{
long indexBreak = offset;
string fileName = Path.GetFileName(FilePath);
if (fileName.Contains(".txt"))
fileName = fileName.Replace(".txt", "");
System.IO.FileStream file = new System.IO.FileStream(#FilePath, FileMode.Open,FileAccess.Read, FileShare.Read );
Int64 b = file.Length;
MemoryMappedFile MemoryMapped = MemoryMappedFile.CreateFromFile(file, fileName, b, MemoryMappedFileAccess.Read, null, HandleInheritability.Inheritable, false);
using (MemoryMapped)
{
//long offset = 182; // 256 megabytes
//long length = 364; // 512 megabytes
MemoryMappedViewAccessor accessor = MemoryMapped.CreateViewAccessor(offset, length, MemoryMappedFileAccess.Read);
byte byteValue;
int index = 0;
int count = 0;
StringBuilder message = new StringBuilder();
do
{
if (indexBreak == index)
{
count = count + 1;
accessor.Dispose();
string NewRecord = message.ToString();
offset = offset + indexBreak;
length = length + indexBreak;
if (NewRecord.IndexOf("'") != -1)
{ NewRecord = NewRecord.Replace("'", "''"); }
// string Sql = "insert into " + DBTableName + " (ID, DataString) values( " + count + ",'" + NewRecord + "')";
string Code = "";
if (spName == AppConfig.sp_CityStateZip)
{
Code = NewRecord.Trim().Substring(0, 1);
}
InsertUpdateAndDeleteDB(spName, NewRecord.Trim (), Code);
accessor = MemoryMapped.CreateViewAccessor(offset, length, MemoryMappedFileAccess.Read);
message = new StringBuilder();
index = 0;
//break;
}
byteValue = accessor.ReadByte(index);
if (byteValue != 0)
{
char asciiChar = (char)byteValue;
message.Append(asciiChar);
}
index++;
} while (byteValue != 0);
}
MemoryMapped.Dispose();
}
catch (FileNotFoundException)
{
Console.WriteLine("Memory-mapped file does not exist. Run Process A first.");
}
}
Somewhere deep in resource processing code we have something like this:
try {
// Try loading some strings here.
} catch {
// Oops, could not load strings, try another way.
}
Exception is thrown and handled already, it would never show up in your application. The only way to see it is to attach debugger and observe this message.
As you could see from the code, it has nothing to do with your problem. The real problem here is what debugger shows you something you should not see.
Run the solution without debugging mode and it works fine.
This exception means that your program does not get Read access to the file from Windows.
Have you made sure that this file is not locked when your program tries to read it ?
For example, it could be a file that your own program is currently using.
If not, try to run your program as an Administrator and see if it makes a difference.

Could not find a part of the path using File.Copy(source,destination,true) in C# console app

I continue to get the (Could not find a part of the path 'C:\Users(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros) exception. The directory is there on the drive but im not sure why i continue to get this exception.
Extra6DestPath = "C:\Users\(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros\"
static void copyMacrosAndBitmaps(string ExtraSourcePath, string Extra6xDestPath )
{
//counter for total Macro count on network
int Count = 0;
//counter for total bitmap count on network
int iCount = 0;
//Get File information to use for copy
FileInfo[] macrosArray;
FileInfo[] iconArray;
//Get Directory information to use for copy
DirectoryInfo di = new DirectoryInfo(ExtraSourcePath);
DirectoryInfo diIcon = new DirectoryInfo(ExtraIconPath);
//set all macro paths as a string from directory into an array
macrosArray = di.GetFiles("*.ebm");
Count = macrosArray.Length;
//set all bitmaps from directory into an array
iconArray = diIcon.GetFiles("*.bmp");
iCount = iconArray.Length;
//copy macros into destination folder
if (Count == 0)
{
throw new FileNotFoundException("No Macros found to copy");
}
else
{
for (int i = 0; i < Count; i++)
{
File.Copy(Extra6xSourcePathW7 + macrosArray[i].ToString(), Extra6xDestPath + iconArray[i].Name, true);
}
//Copy the bitmaps into destination folder
if (iCount == 0)
{
throw new FileNotFoundException("No bitmaps found to copy");
}
else
{
for (int i = 0; i < Count; i++)
{
File.Copy(ExtraIconPath + iconArray[i].ToString(), Extra6xDestPath + iconArray[i].Name, true);
}
}
}
}
I would first try declaring the path with # symbol, to handle characters that need to be escaped:
Extra6DestPath = #"C:\Users\(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros\"

JavaMail don't read MimeMultipart emails

if (contentType.contains("multipart")) {
// content may contain attachments
Multipart multiPart = (Multipart) message.getContent();
numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
BodyPart part = multiPart.getBodyPart(partCount);
String disposition = part.getDisposition();
InputStream inputStream = null;
if (disposition == null)
{
MimeBodyPart mbp = (MimeBodyPart) multiPart.getBodyPart(partCount);
if (mbp.getContent() instanceof MimeMultipart){
MimeMultipart mmp = (MimeMultipart) mbp.getContent();
messageContent = mmp.getBodyPart(0).getContent().toString();
//System.out.println("bodyContent " + bodyContent);
}
else
{
messageContent = multiPart.getBodyPart(partCount).getContent().toString();
}
}
else if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
// this part is attachment
String fileName = part.getFileName();
attachFiles += fileName + ", ";
//part.saveFile(saveDirectory + File.separator + fileName);
}else if (Part.INLINE.equalsIgnoreCase(part.getDisposition())) {
// this part is attachment
String fileName = part.getFileName();
attachFiles += fileName + ", ";
// mbp.saveFile(saveDirectory + File.separator + fileName);
}
else {
// this part may be the message content
messageContent = part.getContent().toString();
}
}
if (attachFiles.length() > 1) {
attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
}
} else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
Object content = message.getContent();
if (content != null) {messageContent = content.toString(); }
}
And now this type of message text / plain, text / html gets well. The problem is the email multipart / related when the message has attachments and content is HTML, then gets some news and some not. I noticed that it is dependent on this line:
messageContent = mmp.getBodyPart (0). getContent (). toString ();
If instead of "0" is "partCount" gets all but one particular, if instead of "0" is "1" gets me this one specific and does not charge others. numberOfParts this one particular message is "3" and the other "2". I have no idea what is wrong, maybe wrong parameters are passed?
I'm not really sure what problem you're trying to solve, but just in case this JavaMail FAQ entry might be helpful.
multipart/mixed and multipart/related are very similar in that they have one main part and a bunch of other parts usually thought of as "attachments". Sometimes the disposition will tell you that it's an attachment, and sometimes it won't. Some mailers aren't very consistent in their use of disposition.
One of the unusual cases is multipart/alternative, but it doesn't sound like that's the problem you're running in to.

Resources