use of javax.mail.MessagingException in project jdk8u_jdk by JetBrains.
the class MailTest method sendMail.
void sendMail() {
try {
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props);
session.setDebug(true);
// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipients(Message.RecipientType.TO, to);
message.setSubject("this is a multipart test");
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("please send also this Content\n ciao!");
multipart.addBodyPart(messageBodyPart1);
BodyPart messageBodyPart2 = new MimeBodyPart();
messageBodyPart2.setContent("<b>please</b> send also this Content <br>ciao!", "text/html; charset=UTF-8");
multipart.addBodyPart(messageBodyPart2);
message.setContent(multipart);
/*
Transport tr = session.getTransport("smtp");
tr.connect(host,user, password);
tr.sendMessage(message,InternetAddress.parse(to));
tr.close();
*/
ByteArrayOutputStream baos = new ByteArrayOutputStream();
message.writeTo(baos);
String output = baos.toString();
System.out.println("output = " + output);
if (output.contains("also this Content")) {
System.out.println("Test PASSED.");
} else {
System.out.println("Test FAILED, missing content.");
throw new IllegalStateException("Test FAILED, missing content.");
}
} catch (MessagingException ignored) {
} catch (IOException ignored) {
}
}
use of javax.mail.MessagingException in project symmetric-ds by JumpMind.
the class MailService method testTransport.
public String testTransport(TypedProperties prop) {
String error = null;
Transport transport = null;
try {
Session session = Session.getInstance(getJavaMailProperties(prop));
transport = session.getTransport(prop.get(ParameterConstants.SMTP_TRANSPORT, "smtp"));
if (prop.is(ParameterConstants.SMTP_USE_AUTH, false)) {
transport.connect(prop.get(ParameterConstants.SMTP_USER), prop.get(ParameterConstants.SMTP_PASSWORD));
} else {
transport.connect();
}
} catch (NoSuchProviderException e) {
error = getNestedErrorMessage(e);
} catch (MessagingException e) {
error = getNestedErrorMessage(e);
} finally {
try {
if (transport != null) {
transport.close();
}
} catch (MessagingException e) {
}
}
return error;
}
use of javax.mail.MessagingException in project symmetric-ds by JumpMind.
the class MailService method sendEmail.
protected String sendEmail(String subject, String text, String recipients, Properties prop, String transportType, boolean useAuth, String user, String password) {
Session session = Session.getInstance(prop);
ByteArrayOutputStream ba = null;
if (log.isDebugEnabled()) {
session.setDebug(true);
ba = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(ba);
session.setDebugOut(ps);
}
Transport transport;
try {
transport = session.getTransport(transportType);
} catch (NoSuchProviderException e) {
log.error("Failure while obtaining transport", e);
return getNestedErrorMessage(e);
}
try {
if (useAuth) {
transport.connect(user, password);
} else {
transport.connect();
}
} catch (MessagingException e) {
log.error("Failure while connecting to transport", e);
return getNestedErrorMessage(e);
}
try {
MimeMessage message = new MimeMessage(session);
message.setSentDate(new Date());
message.setRecipients(RecipientType.BCC, recipients);
message.setSubject(subject);
message.setText(text);
try {
transport.sendMessage(message, message.getAllRecipients());
} catch (MessagingException e) {
log.error("Failure while sending notification", e);
return getNestedErrorMessage(e);
}
} catch (MessagingException e) {
log.error("Failure while preparing notification", e);
return e.getMessage();
} finally {
try {
transport.close();
} catch (MessagingException e) {
}
}
if (log.isDebugEnabled()) {
log.debug(ba.toString());
}
return null;
}
use of javax.mail.MessagingException in project GNS by MobilityFirst.
the class Email method simpleMail.
/**
*
* @param subject
* @param recipient
* @param text
* @param suppressWarning
* @return true if the mail was sent
*/
public static boolean simpleMail(String subject, String recipient, String text, boolean suppressWarning) {
try {
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
Properties props = new Properties();
props.setProperty("mail.smtp.ssl.enable", "true");
//props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getInstance(props);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(Config.getGlobalString(GNSConfig.GNSC.SUPPORT_EMAIL)));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
message.setSubject(subject);
message.setText(text);
SMTPTransport t = (SMTPTransport) session.getTransport("smtp");
try {
t.connect(SMTP_HOST, Config.getGlobalString(GNSConfig.GNSC.ADMIN_EMAIL), Config.getGlobalString(GNSConfig.GNSC.ADMIN_PASSWORD));
t.sendMessage(message, message.getAllRecipients());
getLogger().log(Level.FINE, "Email response: {0}", t.getLastServerResponse());
} finally {
t.close();
}
getLogger().log(Level.FINE, "Successfully sent email to {0} with message: {1}", new Object[] { recipient, text });
return true;
} catch (GeneralSecurityException | MessagingException e) {
if (!suppressWarning) {
getLogger().log(Level.WARNING, "Unable to send email: {0}", e);
}
return false;
}
}
use of javax.mail.MessagingException in project voldemort by voldemort.
the class GetAllResponseSender method sendResponse.
/**
* Sends nested multipart response. Outer multipart wraps all the keys
* requested. Each key has a separate multipart for the versioned values.
*/
@Override
public void sendResponse(StoreStats performanceStats, boolean isFromLocalZone, long startTimeInMs) throws Exception {
/*
* Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage.
* However when writing to the outputStream we only send the multiPart object and not the entire
* mimeMessage. This is intentional.
*
* In the earlier version of this code we used to create a multiPart object and just send that multiPart
* across the wire.
*
* However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates
* a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated
* immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the
* enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders()
* on the body part. It's this updateHeaders call that transfers the content type from the
* DataHandler to the part's MIME Content-Type header.
*
* To make sure that the Content-Type headers are being updated (without changing too much code), we decided
* to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart.
* This is to make sure multiPart's headers are updated accurately.
*/
MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
// multiPartKeys is the outer multipart
MimeMultipart multiPartKeys = new MimeMultipart();
ByteArrayOutputStream keysOutputStream = new ByteArrayOutputStream();
for (Entry<ByteArray, List<Versioned<byte[]>>> entry : versionedResponses.entrySet()) {
ByteArray key = entry.getKey();
String base64Key = RestUtils.encodeVoldemortKey(key.get());
String contentLocationKey = "/" + this.storeName + "/" + base64Key;
// Create the individual body part - for each key requested
MimeBodyPart keyBody = new MimeBodyPart();
try {
// Add the right headers
keyBody.addHeader(CONTENT_TYPE, "application/octet-stream");
keyBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
keyBody.addHeader(CONTENT_LOCATION, contentLocationKey);
} catch (MessagingException me) {
logger.error("Exception while constructing key body headers", me);
keysOutputStream.close();
throw me;
}
// multiPartValues is the inner multipart
MimeMultipart multiPartValues = new MimeMultipart();
for (Versioned<byte[]> versionedValue : entry.getValue()) {
byte[] responseValue = versionedValue.getValue();
VectorClock vectorClock = (VectorClock) versionedValue.getVersion();
String eTag = RestUtils.getSerializedVectorClock(vectorClock);
numVectorClockEntries += vectorClock.getVersionMap().size();
// Create the individual body part - for each versioned value of
// a key
MimeBodyPart valueBody = new MimeBodyPart();
try {
// Add the right headers
valueBody.addHeader(CONTENT_TYPE, "application/octet-stream");
valueBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
valueBody.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag);
valueBody.setContent(responseValue, "application/octet-stream");
valueBody.addHeader(RestMessageHeaders.CONTENT_LENGTH, Integer.toString(responseValue.length));
multiPartValues.addBodyPart(valueBody);
} catch (MessagingException me) {
logger.error("Exception while constructing value body part", me);
keysOutputStream.close();
throw me;
}
}
try {
// Add the inner multipart as the content of the outer body part
keyBody.setContent(multiPartValues);
multiPartKeys.addBodyPart(keyBody);
} catch (MessagingException me) {
logger.error("Exception while constructing key body part", me);
keysOutputStream.close();
throw me;
}
}
message.setContent(multiPartKeys);
message.saveChanges();
try {
multiPartKeys.writeTo(keysOutputStream);
} catch (Exception e) {
logger.error("Exception while writing mutipart to output stream", e);
throw e;
}
ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();
responseContent.writeBytes(keysOutputStream.toByteArray());
// Create the Response object
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
// Set the right headers
response.setHeader(CONTENT_TYPE, "multipart/binary");
response.setHeader(CONTENT_TRANSFER_ENCODING, "binary");
// Copy the data into the payload
response.setContent(responseContent);
response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());
// Write the response to the Netty Channel
if (logger.isDebugEnabled()) {
String keyStr = getKeysHexString(this.versionedResponses.keySet());
debugLog("GET_ALL", this.storeName, keyStr, startTimeInMs, System.currentTimeMillis(), numVectorClockEntries);
}
this.messageEvent.getChannel().write(response);
if (performanceStats != null && isFromLocalZone) {
recordStats(performanceStats, startTimeInMs, Tracked.GET_ALL);
}
keysOutputStream.close();
}
Aggregations