use of javax.mail.SendFailedException in project OpenOLAT by OpenOLAT.
the class MailManagerImpl method sendMessage.
@Override
public void sendMessage(MimeMessage msg, MailerResult result) {
if (msg == null)
return;
String smtpFrom = WebappHelper.getMailConfig("smtpFrom");
if (StringHelper.containsNonWhitespace(smtpFrom)) {
try {
SMTPMessage smtpMsg = new SMTPMessage(msg);
smtpMsg.setEnvelopeFrom(smtpFrom);
msg = smtpMsg;
} catch (MessagingException e) {
log.error("", e);
}
}
try {
if (Settings.isJUnitTest()) {
// we want not send really e-mails
} else if (mailModule.isMailHostEnabled() && result.getReturnCode() == MailerResult.OK) {
// now send the mail
if (Settings.isDebuging()) {
logMessage(msg);
}
Transport.send(msg);
} else if (Settings.isDebuging() && result.getReturnCode() == MailerResult.OK) {
logMessage(msg);
} else {
result.setReturnCode(MailerResult.MAILHOST_UNDEFINED);
}
} catch (SendFailedException e) {
result.setReturnCode(MailerResult.RECIPIENT_ADDRESS_ERROR);
result.addInvalidAddresses(e.getInvalidAddresses());
result.addInvalidAddresses(e.getValidUnsentAddresses());
result.setErrorMessage(e.getMessage());
log.warn("Could not send mail", e);
} catch (MessagingException e) {
result.setReturnCode(MailerResult.SEND_GENERAL_ERROR);
result.setErrorMessage(e.getMessage());
log.warn("Could not send mail", e);
}
}
use of javax.mail.SendFailedException in project xwiki-platform by xwiki.
the class MailSenderPlugin method sendMails.
/**
* Send a Collection of Mails (multiple emails)
*
* @param emails Mail Collection
* @return True in any case (TODO ?)
*/
public boolean sendMails(Collection<Mail> emails, MailConfiguration mailConfiguration, XWikiContext context) throws MessagingException, UnsupportedEncodingException {
Session session = null;
Transport transport = null;
int emailCount = emails.size();
int count = 0;
int sendFailedCount = 0;
try {
for (Iterator<Mail> emailIt = emails.iterator(); emailIt.hasNext(); ) {
count++;
Mail mail = emailIt.next();
LOGGER.info("Sending email: " + mail.toString());
if ((transport == null) || (session == null)) {
// initialize JavaMail Session and Transport
Properties props = initProperties(mailConfiguration);
session = Session.getInstance(props, null);
transport = session.getTransport("smtp");
if (!mailConfiguration.usesAuthentication()) {
// no auth info - typical 127.0.0.1 open relay scenario
transport.connect();
} else {
// auth info present - typical with external smtp server
transport.connect(mailConfiguration.getSmtpUsername(), mailConfiguration.getSmtpPassword());
}
}
try {
MimeMessage message = createMimeMessage(mail, session, context);
if (message == null) {
continue;
}
transport.sendMessage(message, message.getAllRecipients());
// close the connection every other 100 emails
if ((count % 100) == 0) {
try {
if (transport != null) {
transport.close();
}
} catch (MessagingException ex) {
LOGGER.error("MessagingException has occured.", ex);
}
transport = null;
session = null;
}
} catch (SendFailedException ex) {
sendFailedCount++;
LOGGER.error("SendFailedException has occured.", ex);
LOGGER.error("Detailed email information" + mail.toString());
if (emailCount == 1) {
throw ex;
}
if ((emailCount != 1) && (sendFailedCount > 10)) {
throw ex;
}
} catch (MessagingException mex) {
LOGGER.error("MessagingException has occured.", mex);
LOGGER.error("Detailed email information" + mail.toString());
if (emailCount == 1) {
throw mex;
}
} catch (XWikiException e) {
LOGGER.error("XWikiException has occured.", e);
} catch (IOException e) {
LOGGER.error("IOException has occured.", e);
}
}
} finally {
try {
if (transport != null) {
transport.close();
}
} catch (MessagingException ex) {
LOGGER.error("MessagingException has occured.", ex);
}
LOGGER.info("sendEmails: Email count = " + emailCount + " sent count = " + count);
}
return true;
}
use of javax.mail.SendFailedException in project ofbiz-framework by apache.
the class EmailServices method sendMail.
/**
* Basic JavaMail Service
*@param ctx The DispatchContext that this service is operating in
*@param context Map containing the input parameters
*@return Map with the result of the service, the output parameters
*/
public static Map<String, Object> sendMail(DispatchContext ctx, Map<String, ? extends Object> context) {
Delegator delegator = ctx.getDelegator();
String communicationEventId = (String) context.get("communicationEventId");
String orderId = (String) context.get("orderId");
String returnId = (String) context.get("returnId");
Locale locale = (Locale) context.get("locale");
if (communicationEventId != null) {
Debug.logInfo("SendMail Running, for communicationEventId : " + communicationEventId, module);
}
Map<String, Object> results = ServiceUtil.returnSuccess();
String subject = (String) context.get("subject");
subject = FlexibleStringExpander.expandString(subject, context);
String partyId = (String) context.get("partyId");
String body = (String) context.get("body");
List<Map<String, Object>> bodyParts = UtilGenerics.checkList(context.get("bodyParts"));
GenericValue userLogin = (GenericValue) context.get("userLogin");
results.put("communicationEventId", communicationEventId);
results.put("partyId", partyId);
results.put("subject", subject);
if (UtilValidate.isNotEmpty(orderId)) {
results.put("orderId", orderId);
}
if (UtilValidate.isNotEmpty(returnId)) {
results.put("returnId", returnId);
}
if (UtilValidate.isNotEmpty(body)) {
body = FlexibleStringExpander.expandString(body, context);
results.put("body", body);
}
if (UtilValidate.isNotEmpty(bodyParts)) {
results.put("bodyParts", bodyParts);
}
results.put("userLogin", userLogin);
String sendTo = (String) context.get("sendTo");
String sendCc = (String) context.get("sendCc");
String sendBcc = (String) context.get("sendBcc");
// check to see if we should redirect all mail for testing
String redirectAddress = EntityUtilProperties.getPropertyValue("general", "mail.notifications.redirectTo", delegator);
if (UtilValidate.isNotEmpty(redirectAddress)) {
StringBuilder sb = new StringBuilder();
sb.append(" [To: ").append(sendTo);
if (UtilValidate.isNotEmpty(sendCc)) {
sb.append(", Cc: ").append(sendCc);
}
if (UtilValidate.isNotEmpty(sendBcc)) {
sb.append(", Bcc: ").append(sendBcc);
}
sb.append("]");
subject += sb.toString();
sendTo = redirectAddress;
sendCc = null;
sendBcc = null;
if (subject.length() > 255) {
subject = subject.substring(0, 255);
}
}
String sendFrom = (String) context.get("sendFrom");
String sendType = (String) context.get("sendType");
String port = (String) context.get("port");
String socketFactoryClass = (String) context.get("socketFactoryClass");
String socketFactoryPort = (String) context.get("socketFactoryPort");
String socketFactoryFallback = (String) context.get("socketFactoryFallback");
String sendVia = (String) context.get("sendVia");
String authUser = (String) context.get("authUser");
String authPass = (String) context.get("authPass");
String messageId = (String) context.get("messageId");
String contentType = (String) context.get("contentType");
Boolean sendPartial = (Boolean) context.get("sendPartial");
Boolean isStartTLSEnabled = (Boolean) context.get("startTLSEnabled");
boolean useSmtpAuth = false;
// define some default
if (sendType == null || sendType.equals("mail.smtp.host")) {
sendType = "mail.smtp.host";
if (UtilValidate.isEmpty(sendVia)) {
sendVia = EntityUtilProperties.getPropertyValue("general", "mail.smtp.relay.host", "localhost", delegator);
}
if (UtilValidate.isEmpty(authUser)) {
authUser = EntityUtilProperties.getPropertyValue("general", "mail.smtp.auth.user", delegator);
}
if (UtilValidate.isEmpty(authPass)) {
authPass = EntityUtilProperties.getPropertyValue("general", "mail.smtp.auth.password", delegator);
}
if (UtilValidate.isNotEmpty(authUser)) {
useSmtpAuth = true;
}
if (UtilValidate.isEmpty(port)) {
port = EntityUtilProperties.getPropertyValue("general", "mail.smtp.port", delegator);
}
if (UtilValidate.isEmpty(socketFactoryPort)) {
socketFactoryPort = EntityUtilProperties.getPropertyValue("general", "mail.smtp.socketFactory.port", delegator);
}
if (UtilValidate.isEmpty(socketFactoryClass)) {
socketFactoryClass = EntityUtilProperties.getPropertyValue("general", "mail.smtp.socketFactory.class", delegator);
}
if (UtilValidate.isEmpty(socketFactoryFallback)) {
socketFactoryFallback = EntityUtilProperties.getPropertyValue("general", "mail.smtp.socketFactory.fallback", "false", delegator);
}
if (sendPartial == null) {
sendPartial = EntityUtilProperties.propertyValueEqualsIgnoreCase("general", "mail.smtp.sendpartial", "true", delegator) ? true : false;
}
if (isStartTLSEnabled == null) {
isStartTLSEnabled = EntityUtilProperties.propertyValueEqualsIgnoreCase("general", "mail.smtp.starttls.enable", "true", delegator);
}
} else if (sendVia == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendMissingParameterSendVia", locale));
}
if (contentType == null) {
contentType = "text/html";
}
if (UtilValidate.isNotEmpty(bodyParts)) {
contentType = "multipart/mixed";
}
results.put("contentType", contentType);
Session session;
MimeMessage mail;
try {
Properties props = System.getProperties();
props.put(sendType, sendVia);
if (UtilValidate.isNotEmpty(port)) {
props.put("mail.smtp.port", port);
}
if (UtilValidate.isNotEmpty(socketFactoryPort)) {
props.put("mail.smtp.socketFactory.port", socketFactoryPort);
}
if (UtilValidate.isNotEmpty(socketFactoryClass)) {
props.put("mail.smtp.socketFactory.class", socketFactoryClass);
}
if (UtilValidate.isNotEmpty(socketFactoryFallback)) {
props.put("mail.smtp.socketFactory.fallback", socketFactoryFallback);
}
if (useSmtpAuth) {
props.put("mail.smtp.auth", "true");
}
if (sendPartial != null) {
props.put("mail.smtp.sendpartial", sendPartial ? "true" : "false");
}
if (isStartTLSEnabled) {
props.put("mail.smtp.starttls.enable", "true");
}
session = Session.getInstance(props);
boolean debug = EntityUtilProperties.propertyValueEqualsIgnoreCase("general", "mail.debug.on", "Y", delegator);
session.setDebug(debug);
mail = new MimeMessage(session);
if (messageId != null) {
mail.setHeader("In-Reply-To", messageId);
mail.setHeader("References", messageId);
}
mail.setFrom(new InternetAddress(sendFrom));
mail.setSubject(subject, "UTF-8");
mail.setHeader("X-Mailer", "Apache OFBiz, The Open For Business Project");
mail.setSentDate(new Date());
mail.addRecipients(Message.RecipientType.TO, sendTo);
if (UtilValidate.isNotEmpty(sendCc)) {
mail.addRecipients(Message.RecipientType.CC, sendCc);
}
if (UtilValidate.isNotEmpty(sendBcc)) {
mail.addRecipients(Message.RecipientType.BCC, sendBcc);
}
if (UtilValidate.isNotEmpty(bodyParts)) {
// check for multipart message (with attachments)
// BodyParts contain a list of Maps items containing content(String) and type(String) of the attachement
MimeMultipart mp = new MimeMultipart();
Debug.logInfo(bodyParts.size() + " multiparts found", module);
for (Map<String, Object> bodyPart : bodyParts) {
Object bodyPartContent = bodyPart.get("content");
MimeBodyPart mbp = new MimeBodyPart();
if (bodyPartContent instanceof String) {
Debug.logInfo("part of type: " + bodyPart.get("type") + " and size: " + bodyPart.get("content").toString().length(), module);
mbp.setText((String) bodyPartContent, "UTF-8", ((String) bodyPart.get("type")).substring(5));
} else if (bodyPartContent instanceof byte[]) {
ByteArrayDataSource bads = new ByteArrayDataSource((byte[]) bodyPartContent, (String) bodyPart.get("type"));
Debug.logInfo("part of type: " + bodyPart.get("type") + " and size: " + ((byte[]) bodyPartContent).length, module);
mbp.setDataHandler(new DataHandler(bads));
} else if (bodyPartContent instanceof DataHandler) {
mbp.setDataHandler((DataHandler) bodyPartContent);
} else {
mbp.setDataHandler(new DataHandler(bodyPartContent, (String) bodyPart.get("type")));
}
String fileName = (String) bodyPart.get("filename");
if (fileName != null) {
mbp.setFileName(fileName);
}
mp.addBodyPart(mbp);
}
mail.setContent(mp);
mail.saveChanges();
} else {
// create the singelpart message
if (contentType.startsWith("text")) {
mail.setText(body, "UTF-8", contentType.substring(5));
} else {
mail.setContent(body, contentType);
}
mail.saveChanges();
}
} catch (MessagingException e) {
Debug.logError(e, "MessagingException when creating message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]", module);
Debug.logError("Email message that could not be created to [" + sendTo + "] had context: " + context, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendMessagingException", UtilMisc.toMap("sendTo", sendTo, "sendFrom", sendFrom, "sendCc", sendCc, "sendBcc", sendBcc, "subject", subject), locale));
}
// check to see if sending mail is enabled
String mailEnabled = EntityUtilProperties.getPropertyValue("general", "mail.notifications.enabled", "N", delegator);
if (!"Y".equalsIgnoreCase(mailEnabled)) {
// no error; just return as if we already processed
Debug.logImportant("Mail notifications disabled in general.properties; mail with subject [" + subject + "] not sent to addressee [" + sendTo + "]", module);
if (Debug.verboseOn())
Debug.logVerbose("What would have been sent, the addressee: " + sendTo + " subject: " + subject + " context: " + context, module);
results.put("messageWrapper", new MimeMessageWrapper(session, mail));
return results;
}
Transport trans = null;
try {
trans = session.getTransport("smtp");
if (!useSmtpAuth) {
trans.connect();
} else {
trans.connect(sendVia, authUser, authPass);
}
trans.sendMessage(mail, mail.getAllRecipients());
results.put("messageWrapper", new MimeMessageWrapper(session, mail));
results.put("messageId", mail.getMessageID());
trans.close();
} catch (SendFailedException e) {
// message code prefix may be used by calling services to determine the cause of the failure
Debug.logError(e, "[ADDRERR] Address error when sending message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]", module);
List<SMTPAddressFailedException> failedAddresses = new LinkedList<>();
Exception nestedException = null;
while ((nestedException = e.getNextException()) != null && nestedException instanceof MessagingException) {
if (nestedException instanceof SMTPAddressFailedException) {
SMTPAddressFailedException safe = (SMTPAddressFailedException) nestedException;
Debug.logError("Failed to send message to [" + safe.getAddress() + "], return code [" + safe.getReturnCode() + "], return message [" + safe.getMessage() + "]", module);
failedAddresses.add(safe);
break;
}
}
Boolean sendFailureNotification = (Boolean) context.get("sendFailureNotification");
if (sendFailureNotification == null || sendFailureNotification) {
sendFailureNotification(ctx, context, mail, failedAddresses);
results.put("messageWrapper", new MimeMessageWrapper(session, mail));
try {
results.put("messageId", mail.getMessageID());
trans.close();
} catch (MessagingException e1) {
Debug.logError(e1, module);
}
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendAddressError", UtilMisc.toMap("sendTo", sendTo, "sendFrom", sendFrom, "sendCc", sendCc, "sendBcc", sendBcc, "subject", subject), locale));
}
} catch (MessagingException e) {
// message code prefix may be used by calling services to determine the cause of the failure
Debug.logError(e, "[CON] Connection error when sending message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]", module);
Debug.logError("Email message that could not be sent to [" + sendTo + "] had context: " + context, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendConnectionError", UtilMisc.toMap("sendTo", sendTo, "sendFrom", sendFrom, "sendCc", sendCc, "sendBcc", sendBcc, "subject", subject), locale));
}
return results;
}
use of javax.mail.SendFailedException in project ant by apache.
the class MimeMailer method send.
/**
* Send the email.
*
* @throws BuildException if the email can't be sent.
*/
@Override
public void send() {
try {
final Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", String.valueOf(port));
// Aside, the JDK is clearly unaware of the Scottish
// 'session', which involves excessive quantities of
// alcohol :-)
Session sesh;
Authenticator auth = null;
if (SSL) {
try {
final Provider p = Class.forName("com.sun.net.ssl.internal.ssl.Provider").asSubclass(Provider.class).newInstance();
Security.addProvider(p);
} catch (final Exception e) {
throw new BuildException("could not instantiate ssl security provider, check that you have JSSE in your classpath");
}
// SMTP provider
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtps.host", host);
if (isPortExplicitlySpecified()) {
props.put("mail.smtps.port", String.valueOf(port));
props.put("mail.smtp.socketFactory.port", String.valueOf(port));
}
}
if (user != null || password != null) {
props.put("mail.smtp.auth", "true");
auth = new SimpleAuthenticator(user, password);
}
if (isStartTLSEnabled()) {
props.put("mail.smtp.starttls.enable", "true");
}
sesh = Session.getInstance(props, auth);
// create the message
final MimeMessage msg = new MimeMessage(sesh);
final MimeMultipart attachments = new MimeMultipart();
// set the sender
if (from.getName() == null) {
msg.setFrom(new InternetAddress(from.getAddress()));
} else {
msg.setFrom(new InternetAddress(from.getAddress(), from.getName()));
}
// set the reply to addresses
msg.setReplyTo(internetAddresses(replyToList));
msg.setRecipients(Message.RecipientType.TO, internetAddresses(toList));
msg.setRecipients(Message.RecipientType.CC, internetAddresses(ccList));
msg.setRecipients(Message.RecipientType.BCC, internetAddresses(bccList));
// Choosing character set of the mail message
// First: looking it from MimeType
String charset = parseCharSetFromMimeType(message.getMimeType());
if (charset != null) {
// Assign/reassign message charset from MimeType
message.setCharset(charset);
} else {
// Next: looking if charset having explicit definition
charset = message.getCharset();
if (charset == null) {
// Using default
charset = DEFAULT_CHARSET;
message.setCharset(charset);
}
}
// Using javax.activation.DataSource paradigm
final StringDataSource sds = new StringDataSource();
sds.setContentType(message.getMimeType());
sds.setCharset(charset);
if (subject != null) {
msg.setSubject(subject, charset);
}
msg.addHeader("Date", getDate());
if (headers != null) {
for (Header h : headers) {
msg.addHeader(h.getName(), h.getValue());
}
}
final PrintStream out = new PrintStream(sds.getOutputStream());
message.print(out);
out.close();
final MimeBodyPart textbody = new MimeBodyPart();
textbody.setDataHandler(new DataHandler(sds));
attachments.addBodyPart(textbody);
for (File file : files) {
MimeBodyPart body = new MimeBodyPart();
if (!file.exists() || !file.canRead()) {
throw new BuildException("File \"%s\" does not exist or is not readable.", file.getAbsolutePath());
}
final FileDataSource fileData = new FileDataSource(file);
final DataHandler fileDataHandler = new DataHandler(fileData);
body.setDataHandler(fileDataHandler);
body.setFileName(file.getName());
attachments.addBodyPart(body);
}
msg.setContent(attachments);
try {
// Send the message using SMTP, or SMTPS if the host uses SSL
final Transport transport = sesh.getTransport(SSL ? "smtps" : "smtp");
transport.connect(host, user, password);
transport.sendMessage(msg, msg.getAllRecipients());
} catch (final SendFailedException sfe) {
if (!shouldIgnoreInvalidRecipients()) {
throw new BuildException(GENERIC_ERROR, sfe);
}
if (sfe.getValidSentAddresses() == null || sfe.getValidSentAddresses().length == 0) {
throw new BuildException("Couldn't reach any recipient", sfe);
}
Address[] invalid = sfe.getInvalidAddresses();
if (invalid == null) {
invalid = new Address[0];
}
for (Address address : invalid) {
didntReach(address, "invalid", sfe);
}
Address[] validUnsent = sfe.getValidUnsentAddresses();
if (validUnsent == null) {
validUnsent = new Address[0];
}
for (Address address : validUnsent) {
didntReach(address, "valid", sfe);
}
}
} catch (MessagingException | IOException e) {
throw new BuildException(GENERIC_ERROR, e);
}
}
use of javax.mail.SendFailedException in project LAMSADE-tools by LAntoine.
the class Util method sendEmail.
/**
* Sends an email to an address passed by parameter. If there is an error
* other than lack of an Internet connection, the program will exit with a
* stack trace.
*
* @param to_address
* the address to send the email to
* @param filename
* if it's not empty, it will send the file referenced to by the
* filename as an attachment
* @throws IllegalStateException
* @returns 0 if it all went well, -1 if there was some error.
*/
public static int sendEmail(String to_address, String filename) throws IllegalStateException {
int smtp_port = 465;
String smtp_host = "smtp.gmail.com";
String smtp_username = "lamsade.tools@gmail.com";
String smtp_password = "z}}VC_-7{3bk^?*q^qZ4Z>G<5cgN&un&@>wU`gyza]kR(2v/&j!*6*s?H[^w=52e";
Properties props = System.getProperties();
props.put("mail.smtp.host", smtp_host);
props.put("mail.smtps.auth", true);
props.put("mail.smtps.starttls.enable", true);
props.put("mail.smtps.debug", true);
Session session = Session.getInstance(props, null);
Message message = new MimeMessage(session);
logger.info("Trying to send an email to " + to_address);
try {
try {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to_address));
} catch (AddressException e) {
logger.error("There is a problem with the address");
throw new IllegalStateException(e);
}
message.setFrom(new InternetAddress(smtp_username));
message.setSubject("New Mission Order");
message.setText("Email Test Body");
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent("Une conference a été partagée avec vous", "text/html");
MimeBodyPart attachPart = new MimeBodyPart();
String attachFile = filename;
attachPart.attachFile(attachFile);
// adds parts to the multipart
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachPart);
// sets the multipart as message's content
message.setContent(multipart);
Transport transport = session.getTransport("smtps");
try {
transport.connect(smtp_host, smtp_port, smtp_username, smtp_password);
} catch (MessagingException e) {
logger.debug("There seems to be a problem with the connection. Try again later");
return -1;
}
try {
transport.sendMessage(message, message.getAllRecipients());
} catch (SendFailedException e) {
logger.error("Something went wrong trying to send the message");
throw new IllegalStateException(e);
}
transport.close();
} catch (MessagingException e) {
logger.error("Something went wrong with building the message");
throw new IllegalStateException(e);
} catch (IOException e) {
logger.error("Error in trying to add the attachment");
throw new IllegalStateException(e);
}
logger.info("Email sent successfully");
return 0;
}
Aggregations