I have some confusion about message deleting. I have well
connection to email, but code didn't work.
public class GetMyInbox {
public static void main(String[] args) {
Properties prop = System.getProperties();
prop.setProperty("mail.store.protocol", "imaps");
System.out.println("Start connection...");
Session session = Session.getDefaultInstance(prop,null);
try {
Store store = session.getStore("imaps");
store.connect("host", "email","password");
System.out.println("Connected!");
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
Message msg = folder.getMessage(1779);
Address from = msg.getFrom()[0];
List<Message> messages = Arrays.asList(folder.getMessages());
for (Message m : messages) {
if (m.getFrom()[0].equals(from)) {
m.setFlag(Flags.Flag.DELETED, true);
}
}
} catch ...
method equals don't work.
I tried do the same with string
if (m.getFrom()[0].toString().contains("string")){
...
}
Actually, the flag has changed to deleted (it doesn't delete physically). While fetching emails you have to exclude /delete flags.
Related
I am trying to use delegate mail access through javamail. I have configured the delegate access correctly on my system. But when I try to run the following code
import java.util.Properties;
import javax.mail.*;
public class Test {
public static void main(String[] args) {
Properties props = System.getProperties();
props.put("mail.imaps.auth.plain.disable", "true");
props.put("mail.smtp.ssl.enable", "true");
try {
Session session = Session.getInstance(props, null);
session.setDebug(true);
Store store = session.getStore("imaps");
store.connect(mailServerIP, 993, "myAlias/DelegateAlias", "mypassword");
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for (Message message : messages) {
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(2);
}
}
}
it shows me the following error
javax.mail.AuthenticationFailedException: LOGIN failed.
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:715)
at javax.mail.Service.connect(Service.java:364)
at com.adecco.smpt.TestSSL.main(TestSSL.java:26)
If I try to access my mail box instead of shared mailbox everything works well. Is there a different syntax to access the SHARED MAILBOX in JAVA?
I am using the private mail server.
Hello I have problem with my jms code when I try to send over 1000 messages to MDB. Following code:
#Stateless(mappedName = "RequestProcessingQueue")
public class RequestProcessingQueue {
private static final Logger logger = Logger.getLogger(RequestProcessingQueue.class);
#Resource(mappedName = "jmsRequestsFactory")
private ConnectionFactory connectionFactory;
#Resource(mappedName = "jmsRequestsDestination")
private Queue queue;
public void add(String participant, String password, List<Long> documents) throws JmsAppException {
try {
logger.debug("requests to process " + documents);
Connection connecton = connectionFactory.createConnection();
connecton.start();
Session session = connecton.createSession(false, Session.AUTO_ACKNOWLEDGE);
QueueSender sender = (QueueSender) session.createProducer(queue);
Message msg = msg = session.createMessage();
msg.setStringProperty("participant", participant);
msg.setStringProperty("password", password);
for (Long id : documents) {
msg.setLongProperty("request", id);
sender.send(msg);
}
sender.close();
session.close();
connecton.close();
} catch (JMSException e) {
throw new JmsAppException(e);
} catch (Throwable e) {
throw new JmsAppException("Fatal error occured while sending request to be processed", e);
}
}
}
throws
MQJMSRA_DS4001: JMSServiceException on send message:sendMessage: Sending message failed. Connection ID: 2979509408914231552 com.sun.messaging.jms.ra.DirectSession._sendMessage(DirectSession.java:1844) / sendMessage: Sending message failed. Connection ID: 2979509408914231552 com.sun.messaging.jmq.jmsserver.service.imq.IMQDirectService.sendMessage(IMQDirectService.java:1955) / transaction failed: [B4303]: The maximum number of messages [1 000] that the producer can process in a single transaction (TID=2979509408914244096) has been exceeded. Please either limit the # of messages per transaction or increase the imq.transaction.producer.maxNumMsgs property. com.sun.messaging.jmq.jmsserver.data.handlers.DataHandler.routeMessage(DataHandler.java:467)'}
at jms.example.RequestProcessingQueue.add(RequestProcessingQueue.java:48)
I do not understand why cus when I create session I pass false as first param indicating that session is non transactional mode.
Your code does not work because the basic JMS API was designed to work in any environment, not just from within an EJB container. Runtime environment programming restrictions and behaviour are described in the EJB specifications and JavaDoc, in particular javax.jms.Connection.createSession(boolean transacted, int acknowledgeMode).
Your code can be simplified (assuming you're using at least Java 7) to:
#TransactionAttribute(TransactionAttributeType.NOTSUPPORTED)
public void add(String participant, String password, List<Long> documents) throws OgnivoException {
try (Connection connection = connectionFactory.createConnection();
Session session = connection.createSession();
// session.start() not required
MessageProducer sender = session.createProducer(queue)) {
logger.debug("requests to process " + documents);
for (Long id : documents) {
Message msg = msg = session.createMessage();
msg.setStringProperty("participant", participant);
msg.setStringProperty("password", password);
msg.setLongProperty("request", id);
sender.send(msg);
}
} catch (JMSException e) {
throw new JmsAppException(e);
}
// Don't catch throwable because it hides bugs
}
Remember that EJB methods are automatically associated with a transaction unless you specify otherwise. Additionally, be sure to check the javadoc for javax.jms.Connection.createSession() and associated methods, particularly the sections describing behaviour in different runtime environments.
I am developing an application that needs to pull specific filtered messages. I also need to be able to exclude certain messages. for instance, a user may want to exclude all message with the subject, which in this case I would create a SubjectTerm, and put it inside a NotTerm. This is returning 0 messages for some reason. while when i ask just for the subject term, it returns the correct message.The specific service i am trying to use this code with are yahoo and hotmail.
package javaapplication2;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.search.*;
public class imapyahoo {
public static void main(String[] args) {
//set the properties for an ssl connection to the imap server.
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
props.setProperty("mail.imap.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.socketFactory.fallback", "false");
props.setProperty("mail.imap.socketFactory.port", "993");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
System.out.println("connecting....");
store.connect("imap.mail.yahoo.com", "account", "password");
System.out.println("connected");
System.out.println("searching inbox");
Folder inbox = store.getFolder("inbox");
inbox.open(Folder.READ_ONLY);
//apply the search term.
SearchTerm st = new NotTerm(new SubjectTerm("dogs"));
Message[] msgs =inbox.search(st);
System.out.println(msgs.length);
System.out.println("done searching");
//print out the messages
int i =1;
for (Message msg : msgs){
System.out.println(i);
System.out.println(msg.getSubject());
i++;
}
inbox.close(true);
store.close();
} catch (Exception mex) {
mex.printStackTrace();
}
}
}
This is my entire java code. If I comment the line:
objCon = DriverManager.getConnection(props.getString("url")); the mail is sending correctly. Else, its throwing the error - Could not connect to SMTP host: mail.companyname.com, port: 25;
public class PullRec {
private static final Logger LOG_TRACE = Logger.getLogger("debugLogger");
public static void main(String[] args) throws Exception {
Connection objCon = null;
PropertyResourceBundle props;
props = (PropertyResourceBundle) ResourceBundle.getBundle("com.cts.properties.config");
try {
Class.forName(props.getString("dbdriver"));
// If I comment the below line, the sendmail function works perfectly..!!
objCon = DriverManager.getConnection(props.getString("url"));
}
catch(Exception e) {
LOG_TRACE.info("DBConnection.java FILE ERROR: Disconnected due to "+e);
}
sendmail("Test");
}
public static void sendmail(String strBody) {
String to = "sarath#companyname.com";
String from = "sarath#companyname.com";
String host = "mail.companyname.com";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("java.net.preferIPv4Stack","true");
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("CTS Monitor");
message.setContent(strBody,"text/html" );
Transport.send(message);
System.out.println("Sent message successfully....");
}
catch (MessagingException e) {
e.printStackTrace();
}
}
}
Your mail method is clearly setting the SMTP server hostname to "<hostname>". That is never going to work. You need to replace that with the real DNS hostname of the SMTP server you are attempting to use.
(Your from and to addresses are unlikely to work either ...)
If you have done that and it still isn't working, then check that you have got the (real) hostname and port correct, and that the SMTP server on that host / port are alive.
I notice that you have commented out the call to mail(String) which configures the mail server, and I'm not sure what your Mail object is, or what the sendmail method is actually doing.
(Note: this is NOT all of your Java code, because if it was, it doesn't compile!)
I am trying to fetch unread mail from the INBOX from a gmail account. I wrote a small demo program and found that Gmail's pop3 behaves unexpectedly in a number of situations
When you try to get a list of available folders, Pop3 returns just the INBOX and not all the labels while IMAP does it correct. I am in-lining the code here.
POP3
public static Result getPop3FolderList()
{
Properties props = System.getProperties();
props.put("mail.store.protocol", "pop3s");
props.put("mail.pop3.host", "pop.gmail.com");
props.put("mail.pop3.user", Application.email);
props.put("mail.pop3.socketFactory", 995);
props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.pop3.port", 995);
Session session = Session.getInstance(props,new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Application.email, Application.pwd);
}
});
try{
Store store=session.getStore("pop3");
store.connect(Application.email,Application.pwd);
javax.mail.Folder[] folders = store.getDefaultFolder().list("*");
String opHtml = "<ul>";
for (javax.mail.Folder folder : folders) {
if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
opHtml += "<li>" + folder.getFullName()+ "+" + folder.getMessageCount() + "</li>";
}
}
opHtml += "</ul>";
return ok(opHtml).as("text/html");
} catch(MessagingException e) {
return ok("Error in getting list.<br />" + e.getMessage()).as("text/html");
}
}
IMAP
public static Result getImapFolderList()
{
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props,new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Application.email, Application.pwd);
}
});
javax.mail.Store store = session.getStore("imaps");
store.connect("imap.gmail.com", Application.email, Application.pwd);
javax.mail.Folder[] folders = store.getDefaultFolder().list("*");
String opHtml = "<ul>";
for (javax.mail.Folder folder : folders) {
if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
opHtml += "<li>" + folder.getFullName()+ ":" + folder.getMessageCount() + "</li>";
}
}
opHtml += "</ul>";
return ok(opHtml).as("text/html");
} catch (MessagingException e) {
return ok("Error in getting list.<br />").as("text/html");
}
}
Even When retrieving the mail, when I put the unread mails filter, gmail returns a number of read mail that are not even part of inbox but long archived ones. IMAP, on the other hand behaves expectedly.
Additional Info : I have enabled pop3 only for the new mail and not from the beginning
Am I using the pop3 wrong or is it broken in gmail?
Apparently, POP3 doesn't handle folders. I had the same problem when accessing Exchange mailboxes - IMAP gets folders, POP3 only gets the Inbox.
I found more info here: How to retrieve gmail sub-folders/labels using POP3?