apache pop3 bufferedreader lines end with = (equals) - jakarta-mail

I try to receive some messages from a POP3 mail server using the apache POP3 mail client.
I use a BufferedReader to get messages from my POP3 mail server (retreiveMessage(id)). I have some mails with long lines and I read them with a loop like below. My lines are truncated into several lines ending with the equal sign (=), each line with 76 chars plus the =.
import org.apache.commons.net.pop3.POP3Client;
import org.apache.commons.net.pop3.POP3MessageInfo;
...
POP3Client pop = new POP3Client();
pop.setSocketFactory(SSLSocketFactory.getDefault());
pop.setDefaultTimeout(60000);
pop.connect(MAIL_SEREVR, PORT);
String username = USERNAME;
String password = PASSWORD;
isVerified = pop.login(username, password);
POP3MessageInfo[] messages = pop.listMessages();
for (POP3MessageInfo msginfo : messages) {
Date timestamp = new Date();
BufferedReader reader = (BufferedReader) pop
.retrieveMessage(msginfo.number);
if (reader == null) {
System.err.println("Could not retrieve message header.");
pop.disconnect();
System.exit(1);
}
try {
printMessageInfo(reader, msginfo.number, timestamp);
} catch (Exception e) {
e.printStackTrace();
}
pop.deleteMessage(msginfo.number);
}
pop.logout();
pop.disconnect();
So, I print the messages and since a word is too long, it is truncated like this:
this is a short line, it is OK
andThisIsALongLineWithMoreThan76CharactersButThisIsEmpiricalIJustSeeThatThe=
LineIsTruncatedAtThe76thCHAR
is this a normal behavior? can someone help me?
thanks

It doesn't sound like you're using JavaMail. It you aren't, use it, it will make life easier for you. If you are, explain in more detail what you're doing.

Related

AT command sent SMS received as Flash SMS (Class 0 SMS)

I used this link to send SMS with AT command in WPF.
But when I send SMS with CMGS command, the receiver get the SMS as Flash SMS not usual SMS. My code is as below:
//Check if modem allows you to send and receive SMS messages using AT commands, without the need to decode the binairy PDU field of the SMS first
rval = sp.SendCommand("AT+CMGF=1");
//set Text mode parameters
rval = sp.SendCommand("AT+CSMP=17,167,0,16");
string phonenumber = "xxxxxxxxxxx";
string Message = "test";
rval = sp.SendCommand("AT+CMGS=\"" + phonenumber + "\"");
if (rval.Equals("\r\n> "))
{
rval = sp.SendCommand(Message + char.ConvertFromUtf32(26) );
}
and my SendCommand is as below
public string SendCommand(String commandText)
{
if (!serialPort.IsOpen)
{
try
{
serialPort.Open();
}
catch (Exception ex)
{
LogEvents.InLogFile(ex.Message);
throw new Exception("COM port is busy");
}
}
try
{
serialPort.DiscardOutBuffer();
serialPort.DiscardInBuffer();
buff = "";
serialPort.Write(commandText + "\r");
Thread.Sleep(serialPort.ReadTimeout);
return buff;
}
catch (Exception)
{
throw new Exception("Error connection");
}
}
Can any one help me?
My other references:
developershome,
Sayeda Anila Nusrat
The fourth parameter in AT+CSMP sets the coding scheme, i don't remember in which document i've found the coding of this byte but bit 7 sets whether the message should be discarded after showing it class 0 or stored
You should set this bit to 1 to make it storable, so changing
rval = sp.SendCommand("AT+CSMP=17,167,0,16");
to
rval = sp.SendCommand("AT+CSMP=17,167,0,144");
should do the work
Bit 0 (i.e., the least significant bit) of the fourth parameter of the AT+CSMP command is a flag for whether the SMS will be flashed (when 0) or saved (when 1).
Simply put: An even number for 4th parameter will NOT save the message, while an odd number will.
Change AT+CSMP=17,167,0,16 to AT+CSMP=17,167,0,0.

IMAPAddress Exception - Hello, it's me again

Yesterday I asked on this site for an Exception that I didn't know how to handle, and I luckily found an answer in a very short time. Well.. here's another one. The class is the same of the other question: when I download messages from the imap server and handle them into an array, it gives me IMAPAddress Exception. This time I really don't know what I could do, I don't want to use POP3 because I just want to see emails stored on the server, not really handle them. Thank you for the attention.
Here's the code:
ScaricaEmail(String host,String porta,String user,String pw)
{
this.host=host;
this.porta=porta;
nick=user;
this.pw=pw;
}
public static Object[][] checkMail(String cartella)
{
Object[][] tabella;
try
{
Properties propvals = new Properties();
propvals.put("mail.imaps.host", host);
propvals.put("mail.imaps.port", porta);
propvals.put("mail.imaps.starttls.enable", "true");
propvals.put("mail.imaps.ssl.trust", "*");
Session emailSessionObj = Session.getDefaultInstance(propvals);
//Create IMAP store object and connect with the server
Store storeObj = emailSessionObj.getStore("imaps");
storeObj.connect(host, nick, pw);
//Create folder object and open it in read-only mode
Folder emailFolderObj = storeObj.getFolder(cartella);
emailFolderObj.open(Folder.READ_ONLY);
//Fetch messages from the folder and print in a loop
Message[] messageobjs = emailFolderObj.getMessages();
tabella=new Object[messageobjs.length][6];
for(int i = 1; i <= messageobjs.length; i++)
{
Message m = messageobjs[i-1];
String mimeType = m.getContentType();
Object[] risultati=new String[6];
risultati[i-1]=m.getFrom()[i-1]; //Here's where I get the Exception
risultati[i-1]=m.getSubject();
risultati[i-1]=getTestoDaMessaggio(m);
risultati[i-1]=getContoAllegati(m);
risultati[i-1]=m.getSentDate();
risultati[i-1]=0;
tabella[i-1]=risultati;
}
emailFolderObj.close(false);
storeObj.close();
}
catch (Exception exp)
{
exp.printStackTrace();
tabella=null;
}
return tabella;
}
Here's the output:
java.lang.ArrayStoreException: com.sun.mail.imap.protocol.IMAPAddress
at clientemail.ScaricaEmail.checkMail(ScaricaEmail.java:57)
at clientemail.Home.initComponents(Home.java:240)
at clientemail.Email$4.actionPerformed(Email.java:167)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6525)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6290)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4881)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
Thank you.
Object[] risultati=new String[6];
risultati[i-1]=m.getFrom()[i-1]; //Here's where I get the Exception
Message.getFrom() returns an Address[] and you are getting the first index which is an Address. Address is not a java.lang.String so it can't be stored in a String[].
To make it work you could do something like:
risultati[i-1]=String.valueOf(m.getFrom()[i-1]);
Or you can change the array type:
Object[] risultati=new Object[6];
In general, you avoid coping values to an array and just use the message object.

The message content in a line is becomes 2 lines when reading from InputStream

I am using android JavaMail.
I would like to parse the inputStream of the content myself. So I use
InputStreamReader reader = new InputStreamReader(messages[i].getInputStream());
int value;
StringBuilder out = new StringBuilder();
while((value = reader.read()) != -1) {
out.append((char) value);
}
reader.close();
Log.i(TAG, out.toString());
The original string content is :
<body lang=3D"ZH-TW" link=3D"#0563C1" vlink=3D"#954F72" style=3D"text-justify-trim:punctuation">
But when in the printout result is
<body lang=3D"ZH-TW" link=3D"#0563C1" vlink=3D"#954F72" style=3D"text-justi=
fy-trim:punctuation">
There is extra "=" in the line and it breaks into two line.
"=" seems indicate that the line is not ended yet. How did it happen?
If the line actually ends with =, then how can we differentiate?
Bill, I can work with work around problems with broken IMAP servers
according to the https://www.rfc-editor.org/rfc/rfc3501#section-6.4.5
Arguments: sequence set
message data item names or macro
so it seems that we can fetch with UID specified.
When i am using javamail, even though have the API fetch the message by UID.
javax.mail.Message[] messages = folder.getMessagesByUID(localFolderObject.getUIDNext(),
serverFolderObject.getUIDNext());
for (int i = 0; i < messages.length; ++i) {
// Get the message object from the folder
MimeMessage msg = (MimeMessage) messages[i];
// Copy the message by writing into an byte array.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
msg.writeTo(bos);
bos.close();
Log.i(TAG, bos.toString());
}
catch (IOException e) {
e.printStackTrace();
}
}
the fetch issue as
A38 FETCH 1 (BODY[])
1 is message sequence number, not the UID.
The server wants us to fetch with
A5 UID FETCH 291 (BODY[])
Is there any API "UID Fetch" command for getting the message https://www.rfc-editor.org/rfc/rfc3501#section-6.4.8?
I won't retreive all the messages every time. will keep the previous last NextUID and next time retrieve will start from previous save next UID.
Due to fetch by sequence number, the server always return the first sequnce message instead of the one i want.

Getting path of audio file from sdcard

In my app I tried to pass the file path from one activity to another activity using intent.In my receiving activity I got the file path as "null".But when I print the file in first activity it prints the path.From my second activity I attach that file to mail using Gmailsender.This was the code I tried,
private void startRecord()
{
File file = new File(Environment.getExternalStorageDirectory(), "test.pcm");
try
{
file.createNewFile();
OutputStream outputStream = new FileOutputStream(file);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
DataOutputStream dataOutputStream = new DataOutputStream(bufferedOutputStream);
int minBufferSize = AudioRecord.getMinBufferSize(8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
short[] audioData = new short[minBufferSize];
AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
minBufferSize);
audioRecord.startRecording();
while(recording)
{
int numberOfShort = audioRecord.read(audioData, 0, minBufferSize);
for(int i = 0; i < numberOfShort; i++)
{
dataOutputStream.writeShort(audioData[i]);
}
}
audioRecord.stop();
audioRecord.release();
dataOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
String audiofile;
audiofile=file.getAbsolutePath();
System.out.println("File Path::::"+audiofile);
}
Intent is,
Intent sigout=new Intent(getApplicationContext(),WeeklyendActivity.class);
sigout.putExtra("mnt/sdcard-test.pcm",audiofile);
startActivity(sigout);
In my receiving activity,
String patty=getIntent().getStringExtra("mnt/sdcard-text.pcm");
System.out.println("paathhhy frfom ::"+patty);
It prints null.Can anyone help me how to get the file path.And more thing I am not sure whether the audio would save in that file correctly?
Please anyone help me!!!Thanks in advance!
Based on your information that audioFile is a variable of type File, when you do this:
sigout.putExtra("mnt/sdcard-test.pcm",audiofile);
you are putting a File object in the extras Bundle. Then, when you try to get the extra from the Bundle you do this:
String patty=getIntent().getStringExtra("mnt/sdcard-text.pcm");
However, the object in this extra is of type File, not type String. This is why you are getting null.
If you only want to pass the name of the file, then put the extra like this:
sigout.putExtra("mnt/sdcard-test.pcm",audiofile.getAbsolutePath());

Database problem: how to diagnose and fix the problem?

I created an application which stores values into the database and retrieves the stored data. While running an application in run mode everything seems to work fine (the values are stored and retrieved successfully) but when I run in the debug mode the process throws IllegalStateException and so far haven't found a cause.
The method which retrieves an object Recording is the following:
public Recording getRecording(String filename) {
Recording recording = null;
String where = RECORDING_FILENAME + "='" + filename + "'";
Log.v(TAG, "retrieving recording: filename = " + filename);
try {
cursor = db.query(DATABASE_TABLE_RECORDINGS, new String[]{RECORDING_FILENAME, RECORDING_TITLE, RECORDING_TAGS, RECORDING_PRIVACY_LEVEL, RECORDING_LOCATION, RECORDING_GEO_TAGS, RECORDING_GEO_TAGGING_ENABLED, RECORDING_TIME_SECONDS, RECORDING_SELECTED_COMMUNITY}, where, null, null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
//String filename = c.getString(0);
String title = cursor.getString(1);
String tags = cursor.getString(2);
int privacyLevel = cursor.getInt(3);
String location = cursor.getString(4);
String geoTags = cursor.getString(5);
int iGeoTaggingEnabled = cursor.getInt(6);
String recordingTime = cursor.getString(7);
String communityID = cursor.getString(8);
cursor.close();
recording = new Recording(filename, title, tags, privacyLevel, location, geoTags, iGeoTaggingEnabled, recordingTime, communityID);
}
}
catch (SQLException e) {
String msg = e.getMessage();
Log.w(TAG, msg);
recording = null;
}
return recording;
}
and it is called from another class (Settings):
private Recording getRecording(String filename) {
dbAdapter = dbAdapter.open();
Recording recording = dbAdapter.getRecording(filename);
dbAdapter.close();
return recording;
}
While running through the code above everything works fine but then I notice an exception in another thread:
alt text http://img509.imageshack.us/img509/862/illegalstateexception.jpg
and don't know neither what is the possible cause of this exception nor how to debug the code from that thread to diagnose the cause.
I would be very thankful if anyone knew what is the possible issue here.
Thank you!
Looks like that cursor.close() is inside an "if" - that's when SQLiteCursor.finalize() will throw an IllegalStateException (I googled for it). You migh be getting an empty recordset, for instance, if some other process/thread didn't have the time to commit.
Close it always, even if it's result set is empty.
I'd also advice you to access fields by names, not indices, for future compatibility. And do both close()s in finally{} blocks.

Resources