use of javax.mail.Session in project adempiere by adempiere.
the class EMail method send.
/**
* Send Mail direct
* @return OK or error message
*/
public String send() {
log.info("(" + m_Host + ") " + m_from + " -> " + m_to);
m_sentMsg = null;
//
if (!isValid(true)) {
m_sentMsg = "Invalid Data";
return m_sentMsg;
}
// FR [ 402 ]
Session session = null;
try {
session = getSession();
} catch (SecurityException se) {
log.log(Level.WARNING, "Auth=" + m_auth + " - " + se.toString());
m_sentMsg = se.toString();
return se.toString();
} catch (Exception e) {
log.log(Level.SEVERE, "Auth=" + m_auth, e);
m_sentMsg = e.toString();
return e.toString();
}
try {
m_msg = new SMTPMessage(session);
// Addresses
m_msg.setFrom(m_from);
InternetAddress[] rec = getTos();
if (rec.length == 1)
m_msg.setRecipient(Message.RecipientType.TO, rec[0]);
else
m_msg.setRecipients(Message.RecipientType.TO, rec);
rec = getCcs();
if (rec != null && rec.length > 0)
m_msg.setRecipients(Message.RecipientType.CC, rec);
rec = getBccs();
if (rec != null && rec.length > 0)
m_msg.setRecipients(Message.RecipientType.BCC, rec);
if (m_replyTo != null)
m_msg.setReplyTo(new Address[] { m_replyTo });
//
m_msg.setSentDate(new java.util.Date());
m_msg.setHeader("Comments", "AdempiereMail");
// SMTP specifics
m_msg.setAllow8bitMIME(true);
// Send notification on Failure & Success - no way to set envid in Java yet
// Bounce only header
m_msg.setReturnOption(SMTPMessage.RETURN_HDRS);
//
setContent();
m_msg.saveChanges();
log.fine("message =" + m_msg);
//
getTransport(session);
Transport.send(m_msg);
log.fine("Success - MessageID=" + m_msg.getMessageID());
} catch (MessagingException me) {
Exception ex = me;
StringBuffer sb = new StringBuffer("(ME)");
boolean printed = false;
do {
if (ex instanceof SendFailedException) {
SendFailedException sfex = (SendFailedException) ex;
Address[] invalid = sfex.getInvalidAddresses();
if (!printed) {
if (invalid != null && invalid.length > 0) {
sb.append(" - Invalid:");
for (int i = 0; i < invalid.length; i++) sb.append(" ").append(invalid[i]);
}
Address[] validUnsent = sfex.getValidUnsentAddresses();
if (validUnsent != null && validUnsent.length > 0) {
sb.append(" - ValidUnsent:");
for (int i = 0; i < validUnsent.length; i++) sb.append(" ").append(validUnsent[i]);
}
Address[] validSent = sfex.getValidSentAddresses();
if (validSent != null && validSent.length > 0) {
sb.append(" - ValidSent:");
for (int i = 0; i < validSent.length; i++) sb.append(" ").append(validSent[i]);
}
printed = true;
}
if (sfex.getNextException() == null)
sb.append(" ").append(sfex.getLocalizedMessage());
} else if (ex instanceof AuthenticationFailedException) {
sb.append(" - Invalid Username/Password - " + m_auth);
} else // other MessagingException
{
String msg = ex.getLocalizedMessage();
if (msg == null)
sb.append(": ").append(ex.toString());
else {
if (msg.indexOf("Could not connect to SMTP host:") != -1) {
int index = msg.indexOf('\n');
if (index != -1)
msg = msg.substring(0, index);
String cc = "??";
if (m_ctx != null)
cc = m_ctx.getProperty("#AD_Client_ID");
msg += " - AD_Client_ID=" + cc;
}
String className = ex.getClass().getName();
if (className.indexOf("MessagingException") != -1)
sb.append(": ").append(msg);
else
sb.append(" ").append(className).append(": ").append(msg);
}
}
// Next Exception
if (ex instanceof MessagingException)
ex = ((MessagingException) ex).getNextException();
else
ex = null;
} while (// error loop
ex != null);
//
if (CLogMgt.isLevelFinest())
log.log(Level.WARNING, sb.toString(), me);
else
log.log(Level.WARNING, sb.toString());
m_sentMsg = sb.toString();
return sb.toString();
} catch (Exception e) {
log.log(Level.SEVERE, "", e);
m_sentMsg = e.getLocalizedMessage();
return e.getLocalizedMessage();
}
//
if (CLogMgt.isLevelFinest())
dumpMessage();
m_sentMsg = SENT_OK;
return m_sentMsg;
}
use of javax.mail.Session in project jmeter by apache.
the class SMIMEAssertion method getMessageFromResponse.
/**
* extracts a MIME message from the SampleResult
*/
private static MimeMessage getMessageFromResponse(SampleResult response, int messageNumber) throws MessagingException {
SampleResult[] subResults = response.getSubResults();
if (messageNumber >= subResults.length || messageNumber < 0) {
throw new MessagingException("Message number not present in results: " + messageNumber);
}
final SampleResult sampleResult = subResults[messageNumber];
if (log.isDebugEnabled()) {
log.debug("Bytes: {}, Content Type: {}", sampleResult.getBytesAsLong(), sampleResult.getContentType());
}
byte[] data = sampleResult.getResponseData();
Session session = Session.getDefaultInstance(new Properties());
MimeMessage msg = new MimeMessage(session, new ByteArrayInputStream(data));
if (log.isDebugEnabled()) {
log.debug("msg.getSize() = {}", msg.getSize());
}
return msg;
}
use of javax.mail.Session in project jmeter by apache.
the class MailerModel method sendMail.
/**
* Sends a mail with the given parameters using SMTP.
*
* @param from
* the sender of the mail as shown in the mail-client.
* @param vEmails
* all receivers of the mail. The receivers are seperated by
* commas.
* @param subject
* the subject of the mail.
* @param attText
* the message-body.
* @param smtpHost
* the smtp-server used to send the mail.
* @param smtpPort the smtp-server port used to send the mail.
* @param user the login used to authenticate
* @param password the password used to authenticate
* @param mailAuthType {@link MailAuthType} Security policy
* @param debug Flag whether debug messages for the mail session should be generated
* @throws AddressException If mail address is wrong
* @throws MessagingException If building MimeMessage fails
*/
public void sendMail(String from, List<String> vEmails, String subject, String attText, String smtpHost, String smtpPort, final String user, final String password, MailAuthType mailAuthType, boolean debug) throws MessagingException {
InternetAddress[] address = new InternetAddress[vEmails.size()];
for (int k = 0; k < vEmails.size(); k++) {
address[k] = new InternetAddress(vEmails.get(k));
}
// create some properties and get the default Session
Properties props = new Properties();
props.put(MAIL_SMTP_HOST, smtpHost);
// property values are strings
props.put(MAIL_SMTP_PORT, smtpPort);
Authenticator authenticator = null;
if (mailAuthType != MailAuthType.NONE) {
props.put(MAIL_SMTP_AUTH, "true");
switch(mailAuthType) {
case SSL:
props.put(MAIL_SMTP_SOCKETFACTORY_CLASS, "javax.net.ssl.SSLSocketFactory");
break;
case TLS:
props.put(MAIL_SMTP_STARTTLS, "true");
break;
default:
break;
}
}
if (!StringUtils.isEmpty(user)) {
authenticator = new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
};
}
Session session = Session.getInstance(props, authenticator);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setText(attText);
Transport.send(msg);
}
use of javax.mail.Session in project jmeter by apache.
the class MailReaderSampler method sample.
/**
* {@inheritDoc}
*/
@Override
public SampleResult sample(Entry e) {
SampleResult parent = new SampleResult();
// Did sample succeed?
boolean isOK = false;
final boolean deleteMessages = getDeleteMessages();
final String serverProtocol = getServerType();
parent.setSampleLabel(getName());
String samplerString = toString();
parent.setSamplerData(samplerString);
/*
* Perform the sampling
*/
// Start timing
parent.sampleStart();
try {
// Create empty properties
Properties props = new Properties();
if (isUseStartTLS()) {
// $NON-NLS-1$
props.setProperty(mailProp(serverProtocol, "starttls.enable"), TRUE);
if (isEnforceStartTLS()) {
// Requires JavaMail 1.4.2+
// $NON-NLS-1$
props.setProperty(mailProp(serverProtocol, "starttls.require"), TRUE);
}
}
if (isTrustAllCerts()) {
if (isUseSSL()) {
// $NON-NLS-1$
props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"), TRUST_ALL_SOCKET_FACTORY);
// $NON-NLS-1$
props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE);
} else if (isUseStartTLS()) {
// $NON-NLS-1$
props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"), TRUST_ALL_SOCKET_FACTORY);
// $NON-NLS-1$
props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE);
}
} else if (isUseLocalTrustStore()) {
File truststore = new File(getTrustStoreToUse());
log.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
if (!truststore.exists()) {
log.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath());
truststore = new File(FileServer.getFileServer().getBaseDir(), getTrustStoreToUse());
log.info("load local truststore -Attempting to read truststore from: " + truststore.getAbsolutePath());
if (!truststore.exists()) {
log.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath() + ". Local truststore not available, aborting execution.");
throw new IOException("Local truststore file not found. Also not available under : " + truststore.getAbsolutePath());
}
}
if (isUseSSL()) {
// Requires JavaMail 1.4.2+
// $NON-NLS-1$
props.put(// $NON-NLS-1$
mailProp(serverProtocol, "ssl.socketFactory"), new LocalTrustStoreSSLSocketFactory(truststore));
// $NON-NLS-1$
props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE);
} else if (isUseStartTLS()) {
// Requires JavaMail 1.4.2+
// $NON-NLS-1$
props.put(// $NON-NLS-1$
mailProp(serverProtocol, "ssl.socketFactory"), new LocalTrustStoreSSLSocketFactory(truststore));
// $NON-NLS-1$
props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE);
}
}
// Get session
Session session = Session.getInstance(props, null);
// Get the store
Store store = session.getStore(serverProtocol);
store.connect(getServer(), getPortAsInt(), getUserName(), getPassword());
// Get folder
Folder folder = store.getFolder(getFolder());
if (deleteMessages) {
folder.open(Folder.READ_WRITE);
} else {
folder.open(Folder.READ_ONLY);
}
final int messageTotal = folder.getMessageCount();
int n = getNumMessages();
if (n == ALL_MESSAGES || n > messageTotal) {
n = messageTotal;
}
// Get directory
Message[] messages = folder.getMessages(1, n);
StringBuilder pdata = new StringBuilder();
pdata.append(messages.length);
pdata.append(" messages found\n");
parent.setResponseData(pdata.toString(), null);
parent.setDataType(SampleResult.TEXT);
// $NON-NLS-1$
parent.setContentType("text/plain");
final boolean headerOnly = getHeaderOnly();
busy = true;
for (Message message : messages) {
StringBuilder cdata = new StringBuilder();
SampleResult child = new SampleResult();
child.sampleStart();
// $NON-NLS-1$
cdata.append("Message ");
cdata.append(message.getMessageNumber());
child.setSampleLabel(cdata.toString());
child.setSamplerData(cdata.toString());
cdata.setLength(0);
final String contentType = message.getContentType();
// Store the content-type
child.setContentType(contentType);
// RFC 822 uses ascii per default
child.setDataEncoding(RFC_822_DEFAULT_ENCODING);
// Parse the content-type
child.setEncodingAndType(contentType);
if (isStoreMimeMessage()) {
// Don't save headers - they are already in the raw message
ByteArrayOutputStream bout = new ByteArrayOutputStream();
message.writeTo(bout);
// Save raw message
child.setResponseData(bout.toByteArray());
child.setDataType(SampleResult.TEXT);
} else {
// Javadoc for the API says this is OK
@SuppressWarnings("unchecked") Enumeration<Header> hdrs = message.getAllHeaders();
while (hdrs.hasMoreElements()) {
Header hdr = hdrs.nextElement();
String value = hdr.getValue();
try {
value = MimeUtility.decodeText(value);
} catch (UnsupportedEncodingException uce) {
// ignored
}
cdata.append(hdr.getName()).append(": ").append(value).append("\n");
}
child.setResponseHeaders(cdata.toString());
cdata.setLength(0);
if (!headerOnly) {
appendMessageData(child, message);
}
}
if (deleteMessages) {
message.setFlag(Flags.Flag.DELETED, true);
}
child.setResponseOK();
if (child.getEndTime() == 0) {
// Avoid double-call if addSubResult was called.
child.sampleEnd();
}
parent.addSubResult(child);
}
// Close connection
folder.close(true);
store.close();
parent.setResponseCodeOK();
parent.setResponseMessageOK();
isOK = true;
} catch (NoClassDefFoundError | IOException ex) {
// No need to log normally, as we set the status
log.debug("", ex);
// $NON-NLS-1$
parent.setResponseCode("500");
parent.setResponseMessage(ex.toString());
} catch (MessagingException ex) {
// No need to log normally, as we set the status
log.debug("", ex);
// $NON-NLS-1$
parent.setResponseCode("500");
// $NON-NLS-1$
parent.setResponseMessage(ex.toString() + "\n" + samplerString);
} finally {
busy = false;
}
if (parent.getEndTime() == 0) {
// not been set by any child samples
parent.sampleEnd();
}
parent.setSuccessful(isOK);
return parent;
}
use of javax.mail.Session in project jmeter by apache.
the class SMIMEAssertionTest method setUp.
@Before
public void setUp() throws MessagingException, IOException {
Session mailSession = Session.getDefaultInstance(new Properties());
msg = new MimeMessage(mailSession, this.getClass().getResourceAsStream("signed_email.eml"));
parent = new SampleResult();
parent.sampleStart();
parent.addSubResult(createChildSample());
}
Aggregations