use of javax.mail.Message in project Gargoyle by callakrsos.
the class MailPopReceiver method receiveEmail.
public void receiveEmail() {
try {
//1) get the session object
//new Properties();
Properties properties = System.getProperties();
properties.put("mail.pop3.host", popHost);
properties.put("mail.user", userName);
properties.put("mail.from", hostEmailAddr);
properties.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.pop3.socketFactory.port", "995");
properties.put("mail.pop3.port", "995");
properties.setProperty("mail.pop3.socketFactory.fallback", "false");
if (this.proxy != null) {
String hostName = proxy.getHostName();
int port = proxy.getPort();
String value = port + "";
properties.put("proxySet", "true");
properties.put("socksProxyHost", hostName);
properties.put("socksProxyPort", value);
properties.put("http.proxyHost", hostName);
properties.put("http.proxyPort", port + "");
properties.put("https.proxyHost", hostName);
properties.put("https.proxyPort", port + "");
//#####################################
properties.setProperty("proxySet", "true");
properties.setProperty("socksProxyHost", hostName);
properties.setProperty("socksProxyPort", port + "");
properties.setProperty("http.proxyHost", hostName);
properties.setProperty("http.proxyPort", port + "");
properties.setProperty("https.proxyHost", hostName);
properties.setProperty("https.proxyPort", port + "");
}
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(hostEmailAddr, password);
}
};
Session emailSession = Session.getInstance(properties, authenticator);
// Session emailSession = Session.getDefaultInstance(properties);
emailSession.setDebug(debug);
//2) create the POP3 store object and connect with the pop server
// POP3Store emailStore = (POP3Store) emailSession.getStore(type);
URLName url = new URLName(type, popHost, 995, "", hostEmailAddr, password);
POP3SSLStore emailStore = new POP3SSLStore(emailSession, url);
System.out.println(emailStore.isSSL());
emailStore.connect();
System.out.println("connected.");
//3) create the folder object and open it
Folder emailFolder = emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
//4) retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
//5) close the store and folder objects
emailFolder.close(false);
emailStore.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
use of javax.mail.Message in project opennms by OpenNMS.
the class MailTransportMonitor method processMailSubject.
/**
* After a mailbox has been opened, search through the retrieved messages
* for a matching subject.
*
* @param mailParms
* @param mailFolder
* @return a PollStatus indicative of the success of matching a subject or just retieving
* mail folder contents... dependent on configuration.
*/
private PollStatus processMailSubject(final MailTransportParameters mailParms, final Folder mailFolder) {
PollStatus status = PollStatus.unknown();
try {
final String subject = computeMatchingSubject(mailParms);
if (mailFolder.isOpen() && subject != null) {
final Message[] mailMessages = mailFolder.getMessages();
final SearchTerm searchTerm = new SubjectTerm(subject);
final SearchTerm deleteTerm = new HeaderTerm(MTM_HEADER_KEY, m_headerValue);
LOG.debug("searchMailSubject: searching {} message(s) for subject '{}'", mailMessages.length, subject);
boolean delete = false;
boolean found = false;
for (int i = 1; i <= mailMessages.length; i++) {
final Message mailMessage = mailFolder.getMessage(i);
LOG.debug("searchMailSubject: retrieved message subject '{}'", mailMessage.getSubject());
if (mailMessage.match(searchTerm)) {
found = true;
LOG.debug("searchMailSubject: message with subject '{}' found.", subject);
if (mailParms.isEnd2EndTestInProgress()) {
if (!delete)
LOG.debug("searchMailSubject: flagging message with subject '{}' for deletion for end2end test.", subject);
delete = true;
}
}
final boolean deleteAllMail = mailParms.getReadTest().getDeleteAllMail();
final boolean foundMTMHeader = mailMessage.match(deleteTerm);
LOG.debug("searchMailSubject: deleteAllMail = {}, MTM header found = {}", Boolean.toString(deleteAllMail), Boolean.toString(foundMTMHeader));
if (deleteAllMail) {
if (!delete)
LOG.debug("searchMailSubject: flagging message with subject '{}' for deletion because deleteAllMail is set.", subject);
delete = true;
} else if (foundMTMHeader) {
if (!delete)
LOG.debug("searchMailSubject: flagging message with subject '{}' for deletion because we sent it (found header {}={})", subject, MTM_HEADER_KEY, m_headerValue);
delete = true;
}
if (delete) {
mailMessage.setFlag(Flag.DELETED, true);
}
// since we want to delete old messages matchin MTM_HEADER_KEY, we can't break early
// if (found) break;
}
if (!found) {
LOG.debug("searchMailSubject: message with subject: '{}' NOT found.", subject);
status = PollStatus.down("searchMailSubject: matching test message: '" + subject + "', not found.");
} else {
status = PollStatus.available();
}
}
} catch (final MessagingException e) {
return PollStatus.down(e.getLocalizedMessage());
}
return status;
}
use of javax.mail.Message in project opennms by OpenNMS.
the class MailAckProcessor method retrieveAckMessages.
/**
* <p>retrieveAckMessages</p>
*
* @return a {@link java.util.List} object.
* @throws org.opennms.javamail.JavaMailerException if any.
*/
protected List<Message> retrieveAckMessages() throws JavaMailerException {
LOG.debug("retrieveAckMessages: Retrieving messages...");
ReadmailConfig readMailConfig = determineMailReaderConfig();
if (readMailConfig.getReadmailHost() != null) {
final ReadmailHost readmailHost = readMailConfig.getReadmailHost();
final UserAuth userAuth = readMailConfig.getUserAuth();
LOG.debug("retrieveAckMessages: creating JavaReadMailer with config: host: {} port: {} ssl: {} transport: {} user: {} password: {}", readmailHost.getHost(), readmailHost.getPort(), readmailHost.getReadmailProtocol().isSslEnable(), readmailHost.getReadmailProtocol().getTransport(), userAuth == null ? null : userAuth.getUserName(), userAuth == null ? null : userAuth.getPassword());
}
// TODO: make flag for folder open mode
// TODO: Make sure configuration supports flag for deleting acknowledgments
JavaReadMailer readMailer = new JavaReadMailer(readMailConfig, true);
String notifRe = m_ackdDao.getConfig().getNotifyidMatchExpression();
notifRe = notifRe.startsWith("~") ? notifRe.substring(1) : notifRe;
String alarmRe = m_ackdDao.getConfig().getAlarmidMatchExpression();
alarmRe = alarmRe.startsWith("~") ? alarmRe.substring(1) : alarmRe;
Pattern notifPattern = Pattern.compile(notifRe);
Pattern alarmPattern = Pattern.compile(alarmRe);
List<Message> msgs = readMailer.retrieveMessages();
LOG.info("retrieveAckMessages: Iterating {} messages with notif expression: {} and alarm expression: {}", msgs.size(), notifRe, alarmRe);
for (Iterator<Message> iterator = msgs.iterator(); iterator.hasNext(); ) {
Message msg = iterator.next();
try {
String subject = msg.getSubject();
Matcher alarmMatcher = alarmPattern.matcher(subject);
Matcher notifMatcher = notifPattern.matcher(subject);
LOG.debug("retrieveAckMessages: comparing the subject: {}", subject);
if (!(notifMatcher.matches() || alarmMatcher.matches())) {
LOG.debug("retrieveAckMessages: Subject doesn't match either expression.");
iterator.remove();
} else {
// TODO: this just looks wrong
// delete this non-ack message because the acks will get deleted later and the config
// indicates delete all mail from mailbox
LOG.debug("retrieveAckMessages: Subject matched, setting deleted flag");
if (readMailConfig.isDeleteAllMail()) {
msg.setFlag(Flag.DELETED, true);
}
}
} catch (Throwable t) {
LOG.error("retrieveAckMessages: Problem processing message: {}", t);
}
}
return msgs;
}
use of javax.mail.Message in project opennms by OpenNMS.
the class JavaMailAckReaderIT method workingWithSimpleTextMessages.
/**
* tests the ability to create acknowledgments from an email for plain text. This test
* creates a message from scratch rather than reading from an inbox.
*/
@Test
public void workingWithSimpleTextMessages() {
Properties props = new Properties();
Message msg = new MimeMessage(Session.getDefaultInstance(props));
try {
Address[] addrs = new Address[1];
addrs[0] = new InternetAddress("david@opennms.org");
msg.addFrom(addrs);
msg.addRecipient(javax.mail.internet.MimeMessage.RecipientType.TO, addrs[0]);
msg.setSubject("Re: Notice #1234 JavaMailReaderImplTest Test Message");
msg.setText("ACK");
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
List<Message> msgs = new ArrayList<Message>(1);
msgs.add(msg);
List<OnmsAcknowledgment> acks = m_processor.createAcks(msgs);
Assert.assertEquals(1, acks.size());
Assert.assertEquals(AckType.NOTIFICATION, acks.get(0).getAckType());
Assert.assertEquals("david@opennms.org", acks.get(0).getAckUser());
Assert.assertEquals(AckAction.ACKNOWLEDGE, acks.get(0).getAckAction());
Assert.assertEquals(new Integer(1234), acks.get(0).getRefId());
}
use of javax.mail.Message in project opennms by OpenNMS.
the class JavaMailAckReaderIT method workingWithMultiPartMessages.
/**
* tests the ability to create acknowledgments from an email for a multi-part text. This test
* creates a message from scratch rather than reading from an inbox. This message creation
* may not actually represent what comes from a mail server.
*/
@Test
public void workingWithMultiPartMessages() throws JavaMailerException, MessagingException {
List<Message> msgs = new ArrayList<>();
Properties props = new Properties();
Message msg = new MimeMessage(Session.getDefaultInstance(props));
Address[] addrs = new Address[1];
addrs[0] = new InternetAddress("david@opennms.org");
msg.addFrom(addrs);
msg.addRecipient(RecipientType.TO, new InternetAddress("david@opennms.org"));
msg.setSubject("Re: Notice #1234 JavaMailReaderImplTest Test Message");
Multipart mpContent = new MimeMultipart();
BodyPart textBp = new MimeBodyPart();
BodyPart htmlBp = new MimeBodyPart();
textBp.setText("ack");
htmlBp.setContent("<html>\n" + " <head>\n" + " <title>\n" + " Acknowledge\n" + " </title>\n" + " </head>\n" + " <body>\n" + " <h1>\n" + " ack\n" + " </h1>\n" + " </body>\n" + "</html>", "text/html");
mpContent.addBodyPart(textBp);
mpContent.addBodyPart(htmlBp);
msg.setContent(mpContent);
msgs.add(msg);
List<OnmsAcknowledgment> acks = m_processor.createAcks(msgs);
Assert.assertEquals(1, acks.size());
Assert.assertEquals(AckType.NOTIFICATION, acks.get(0).getAckType());
Assert.assertEquals("david@opennms.org", acks.get(0).getAckUser());
Assert.assertEquals(AckAction.ACKNOWLEDGE, acks.get(0).getAckAction());
Assert.assertEquals(new Integer(1234), acks.get(0).getRefId());
}
Aggregations