use of javax.mail.SendFailedException in project zm-mailbox by Zimbra.
the class SmtpTransportTest method dataError.
@Test(timeout = 3000)
public void dataError() throws Exception {
server = MockTcpServer.scenario().sendLine("220 test ready").recvLine().sendLine("250 OK").recvLine().sendLine("250 OK").recvLine().sendLine("250 OK").recvLine().sendLine("451 error").recvLine().build().start(PORT);
Session session = JMSession.getSession();
Transport transport = session.getTransport("smtp");
transport.connect("localhost", PORT, null, null);
String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest";
MimeMessage msg = new ZMimeMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1)));
try {
transport.sendMessage(msg, msg.getAllRecipients());
Assert.fail();
} catch (SendFailedException e) {
Assert.assertEquals(1, e.getValidSentAddresses().length);
Assert.assertEquals(0, e.getValidUnsentAddresses().length);
Assert.assertEquals(0, e.getInvalidAddresses().length);
} finally {
transport.close();
}
server.shutdown(1000);
Assert.assertEquals("EHLO localhost\r\n", server.replay());
Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay());
Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay());
Assert.assertEquals("DATA\r\n", server.replay());
Assert.assertEquals("QUIT\r\n", server.replay());
Assert.assertNull(server.replay());
}
use of javax.mail.SendFailedException in project openolat by klemens.
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 zm-mailbox by Zimbra.
the class ParseMimeMessage method parseMimeMsgSoap.
/**
* Given an {@code <m>} element from SOAP, return us a parsed {@link MimeMessage}, and also fill in the
* {@link MimeMessageData} structure with information we parsed out of it (e.g. contained Invite, msgids, etc etc)
*
* @param msgElem the {@code <m>} element
* @param additionalParts MimeBodyParts that we want to have added to the {@link MimeMessage} (ie things the server
* is adding onto the message)
* @param inviteParser Callback which handles {@code <inv>} embedded invite components
* @param out Holds info about things we parsed out of the message that the caller might want to know about
*/
public static MimeMessage parseMimeMsgSoap(ZimbraSoapContext zsc, OperationContext octxt, Mailbox mbox, Element msgElem, MimeBodyPart[] additionalParts, InviteParser inviteParser, MimeMessageData out, boolean attachMessageFromCache) throws ServiceException {
// msgElem == "<m>" E_MSG
assert (msgElem.getName().equals(MailConstants.E_MSG));
Account target = DocumentHandler.getRequestedAccount(zsc);
ParseMessageContext ctxt = new ParseMessageContext();
ctxt.out = out;
ctxt.zsc = zsc;
ctxt.octxt = octxt;
ctxt.mbox = mbox;
ctxt.use2231 = target.isPrefUseRfc2231();
ctxt.defaultCharset = target.getPrefMailDefaultCharset();
if (Strings.isNullOrEmpty(ctxt.defaultCharset)) {
ctxt.defaultCharset = MimeConstants.P_CHARSET_UTF8;
}
try {
MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSmtpSession(target));
MimeMultipart mmp = null;
Element partElem = msgElem.getOptionalElement(MailConstants.E_MIMEPART);
Element attachElem = msgElem.getOptionalElement(MailConstants.E_ATTACH);
Element inviteElem = msgElem.getOptionalElement(MailConstants.E_INVITE);
boolean hasContent = (partElem != null || inviteElem != null || additionalParts != null);
// || inviteElem != null || additionalParts!=null);
boolean isMultipart = (attachElem != null);
if (isMultipart) {
// may need to change to "digest" later
mmp = new ZMimeMultipart("mixed");
mm.setContent(mmp);
}
// Grab the <inv> part now so we can stick it in a multipart/alternative if necessary
MimeBodyPart[] alternatives = null;
if (inviteElem != null) {
int additionalLen = 0;
if (additionalParts != null) {
additionalLen += additionalParts.length;
}
alternatives = new MimeBodyPart[additionalLen + 1];
int curAltPart = 0;
// goes into the "content" subpart
InviteParserResult result = inviteParser.parse(zsc, octxt, mbox.getAccount(), inviteElem);
if (partElem != null && result.mCal != null) {
// If textual content is provided and there's an invite,
// set the text as DESCRIPTION of the iCalendar. This helps
// clients that ignore alternative text content and only
// displays the DESCRIPTION specified in the iCalendar part.
// (e.g. MS Entourage for Mac)
String desc = getTextPlainContent(partElem);
String html = getTextHtmlContent(partElem);
result.mCal.addDescription(desc, html);
if (result.mInvite != null) {
// It's possible the notes were given in <inv> node only, with no corresponding MIME parts.
if ((desc != null && desc.length() > 0) || (html != null && html.length() > 0)) {
result.mInvite.setDescription(desc, html);
if (desc != null && desc.length() > 0) {
result.mInvite.setFragment(Fragment.getFragment(desc, true));
}
}
}
}
MimeBodyPart mbp = CalendarMailSender.makeICalIntoMimePart(result.mCal);
alternatives[curAltPart++] = mbp;
if (additionalParts != null) {
for (int i = 0; i < additionalParts.length; i++) {
alternatives[curAltPart++] = additionalParts[i];
}
}
} else {
alternatives = additionalParts;
}
// handle the content from the client, if any
if (hasContent) {
setContent(mm, mmp, partElem != null ? partElem : inviteElem, alternatives, ctxt);
}
// attachments go into the toplevel "mixed" part
if (isMultipart && attachElem != null) {
handleAttachments(attachElem, mmp, ctxt, null, Part.ATTACHMENT, attachMessageFromCache);
}
// <m> attributes: id, f[lags], s[ize], d[ate], cid(conv-id), l(parent folder)
// <m> child elements: <e> (email), <s> (subject), <f> (fragment), <mp>, <attach>
MessageAddresses maddrs = new MessageAddresses();
Set<String> headerNames = ImmutableSet.copyOf(Provisioning.getInstance().getConfig().getCustomMimeHeaderNameAllowed());
for (Element elem : msgElem.listElements()) {
String eName = elem.getName();
if (eName.equals(MailConstants.E_ATTACH)) {
// ignore it...
} else if (eName.equals(MailConstants.E_MIMEPART)) {
/* <mp> */
// processMessagePart(mm, elem);
} else if (eName.equals(MailConstants.E_EMAIL)) {
/* <e> */
maddrs.add(elem, ctxt.defaultCharset);
} else if (eName.equals(MailConstants.E_IN_REPLY_TO)) {
/* <irt> */
// mm.setHeader("In-Reply-To", elem.getText());
} else if (eName.equals(MailConstants.E_SUBJECT)) {
/* <su> */
// mm.setSubject(elem.getText(), "utf-8");
} else if (eName.equals(MailConstants.E_FRAG)) {
/* <f> */
ZimbraLog.soap.debug("Ignoring message fragment data");
} else if (eName.equals(MailConstants.E_INVITE)) {
/* <inv> */
// Already processed above. Ignore it.
} else if (eName.equals(MailConstants.E_CAL_TZ)) {
/* <tz> */
// Ignore as a special case.
} else if (eName.equals(MailConstants.E_HEADER)) {
// <h>
String name = elem.getAttribute(MailConstants.A_NAME);
if (headerNames.contains(name)) {
mm.addHeader(name, MimeHeader.escape(elem.getText(), Charsets.UTF_8, true));
} else {
throw ServiceException.INVALID_REQUEST("header '" + name + "' not allowed", null);
}
} else {
ZimbraLog.soap.warn("unsupported child element '%s' under parent %s", elem.getName(), msgElem.getName());
}
}
// deal with things that can be either <m> attributes or subelements
String subject = msgElem.getAttribute(MailConstants.E_SUBJECT, "");
mm.setSubject(subject, CharsetUtil.checkCharset(subject, ctxt.defaultCharset));
String irt = cleanReference(msgElem.getAttribute(MailConstants.E_IN_REPLY_TO, null));
if (irt != null) {
mm.setHeader("In-Reply-To", irt);
}
// can have no addresses specified if it's a draft...
if (!maddrs.isEmpty()) {
addAddressHeaders(mm, maddrs);
}
if (!hasContent && !isMultipart) {
mm.setText("", MimeConstants.P_CHARSET_DEFAULT);
}
String flagStr = msgElem.getAttribute(MailConstants.A_FLAGS, "");
if (flagStr.indexOf(Flag.toChar(Flag.ID_HIGH_PRIORITY)) != -1) {
mm.addHeader("X-Priority", "1");
mm.addHeader("Importance", "high");
} else if (flagStr.indexOf(Flag.toChar(Flag.ID_LOW_PRIORITY)) != -1) {
mm.addHeader("X-Priority", "5");
mm.addHeader("Importance", "low");
}
// JavaMail tip: don't forget to call this, it is REALLY confusing.
mm.saveChanges();
return mm;
} catch (UnsupportedEncodingException e) {
throw ServiceException.FAILURE("UnsupportedEncodingException", e);
} catch (SendFailedException e) {
SafeSendFailedException ssfe = new SafeSendFailedException(e);
throw ServiceException.FAILURE("SendFailure", ssfe);
} catch (MessagingException e) {
throw ServiceException.FAILURE("MessagingException", e);
} catch (IOException e) {
throw ServiceException.FAILURE("IOExecption", e);
}
}
use of javax.mail.SendFailedException in project pentaho-platform by pentaho.
the class EmailComponent method executeAction.
@Override
public boolean executeAction() {
EmailAction emailAction = (EmailAction) getActionDefinition();
String messagePlain = emailAction.getMessagePlain().getStringValue();
String messageHtml = emailAction.getMessageHtml().getStringValue();
String subject = emailAction.getSubject().getStringValue();
String to = emailAction.getTo().getStringValue();
String cc = emailAction.getCc().getStringValue();
String bcc = emailAction.getBcc().getStringValue();
String from = emailAction.getFrom().getStringValue(defaultFrom);
if (from.trim().length() == 0) {
from = defaultFrom;
}
if (ComponentBase.debug) {
// $NON-NLS-1$
debug(Messages.getInstance().getString("Email.DEBUG_TO_FROM", to, from));
// $NON-NLS-1$
debug(Messages.getInstance().getString("Email.DEBUG_CC_BCC", cc, bcc));
// $NON-NLS-1$
debug(Messages.getInstance().getString("Email.DEBUG_SUBJECT", subject));
// $NON-NLS-1$
debug(Messages.getInstance().getString("Email.DEBUG_PLAIN_MESSAGE", messagePlain));
// $NON-NLS-1$
debug(Messages.getInstance().getString("Email.DEBUG_HTML_MESSAGE", messageHtml));
}
if ((to == null) || (to.trim().length() == 0)) {
// Get the output stream that the feedback is going into
OutputStream feedbackStream = getFeedbackOutputStream();
if (feedbackStream != null) {
createFeedbackParameter("to", Messages.getInstance().getString("Email.USER_ENTER_EMAIL_ADDRESS"), "", "", // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
true);
// $NON-NLS-1$
setFeedbackMimeType("text/html");
return true;
} else {
return false;
}
}
if (subject == null) {
// $NON-NLS-1$
error(Messages.getInstance().getErrorString("Email.ERROR_0005_NULL_SUBJECT", getActionName()));
return false;
}
if ((messagePlain == null) && (messageHtml == null)) {
// $NON-NLS-1$
error(Messages.getInstance().getErrorString("Email.ERROR_0006_NULL_BODY", getActionName()));
return false;
}
if (getRuntimeContext().isPromptPending()) {
return true;
}
try {
Properties props = new Properties();
final IEmailService service = PentahoSystem.get(IEmailService.class, "IEmailService", PentahoSessionHolder.getSession());
props.put("mail.smtp.host", service.getEmailConfig().getSmtpHost());
props.put("mail.smtp.port", ObjectUtils.toString(service.getEmailConfig().getSmtpPort()));
props.put("mail.transport.protocol", service.getEmailConfig().getSmtpProtocol());
props.put("mail.smtp.starttls.enable", ObjectUtils.toString(service.getEmailConfig().isUseStartTls()));
props.put("mail.smtp.auth", ObjectUtils.toString(service.getEmailConfig().isAuthenticate()));
props.put("mail.smtp.ssl", ObjectUtils.toString(service.getEmailConfig().isUseSsl()));
props.put("mail.smtp.quitwait", ObjectUtils.toString(service.getEmailConfig().isSmtpQuitWait()));
props.put("mail.from.default", service.getEmailConfig().getDefaultFrom());
String fromName = service.getEmailConfig().getFromName();
if (StringUtils.isEmpty(fromName)) {
fromName = Messages.getInstance().getString("schedulerEmailFromName");
}
props.put("mail.from.name", fromName);
props.put("mail.debug", ObjectUtils.toString(service.getEmailConfig().isDebug()));
Session session;
if (service.getEmailConfig().isAuthenticate()) {
props.put("mail.userid", service.getEmailConfig().getUserId());
props.put("mail.password", decrypt(service.getEmailConfig().getPassword()));
Authenticator authenticator = new EmailAuthenticator();
session = Session.getInstance(props, authenticator);
} else {
session = Session.getInstance(props);
}
// debugging is on if either component (xaction) or email config debug is on
if (service.getEmailConfig().isDebug() || ComponentBase.debug) {
session.setDebug(true);
}
// construct the message
MimeMessage msg = new MimeMessage(session);
if (from != null) {
msg.setFrom(new InternetAddress(from));
} else {
// There should be no way to get here
// $NON-NLS-1$
error(Messages.getInstance().getString("Email.ERROR_0012_FROM_NOT_DEFINED"));
}
if ((to != null) && (to.trim().length() > 0)) {
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
}
if ((cc != null) && (cc.trim().length() > 0)) {
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
}
if ((bcc != null) && (bcc.trim().length() > 0)) {
msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
}
if (subject != null) {
msg.setSubject(subject, LocaleHelper.getSystemEncoding());
}
EmailAttachment[] emailAttachments = emailAction.getAttachments();
if ((messagePlain != null) && (messageHtml == null) && (emailAttachments.length == 0)) {
msg.setText(messagePlain, LocaleHelper.getSystemEncoding());
} else if (emailAttachments.length == 0) {
if (messagePlain != null) {
// $NON-NLS-1$
msg.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding());
}
if (messageHtml != null) {
// $NON-NLS-1$
msg.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding());
}
} else {
// need to create a multi-part message...
// create the Multipart and add its parts to it
Multipart multipart = new MimeMultipart();
// create and fill the first message part
if (messageHtml != null) {
// create and fill the first message part
MimeBodyPart htmlBodyPart = new MimeBodyPart();
// $NON-NLS-1$
htmlBodyPart.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding());
multipart.addBodyPart(htmlBodyPart);
}
if (messagePlain != null) {
MimeBodyPart textBodyPart = new MimeBodyPart();
// $NON-NLS-1$
textBodyPart.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding());
multipart.addBodyPart(textBodyPart);
}
for (EmailAttachment element : emailAttachments) {
IPentahoStreamSource source = element.getContent();
if (source == null) {
// $NON-NLS-1$
error(Messages.getInstance().getErrorString("Email.ERROR_0015_ATTACHMENT_FAILED"));
return false;
}
DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);
String attachmentName = element.getName();
if (ComponentBase.debug) {
// $NON-NLS-1$
debug(Messages.getInstance().getString("Email.DEBUG_ADDING_ATTACHMENT", attachmentName));
}
// create the second message part
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
// attach the file to the message
attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
attachmentBodyPart.setFileName(attachmentName);
if (ComponentBase.debug) {
// $NON-NLS-1$
debug(Messages.getInstance().getString("Email.DEBUG_ATTACHMENT_SOURCE", dataSource.getName()));
}
multipart.addBodyPart(attachmentBodyPart);
}
// add the Multipart to the message
msg.setContent(multipart);
}
// $NON-NLS-1$
msg.setHeader("X-Mailer", EmailComponent.MAILER);
msg.setSentDate(new Date());
Transport.send(msg);
if (ComponentBase.debug) {
// $NON-NLS-1$
debug(Messages.getInstance().getString("Email.DEBUG_EMAIL_SUCCESS"));
}
return true;
// TODO: persist the content set for a while...
} catch (SendFailedException e) {
// $NON-NLS-1$
error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e);
/*
* Exception ne; MessagingException sfe = e; while ((ne = sfe.getNextException()) != null && ne instanceof
* MessagingException) { sfe = (MessagingException) ne;
* error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", sfe.toString()), sfe);
* //$NON-NLS-1$ }
*/
} catch (AuthenticationFailedException e) {
// $NON-NLS-1$
error(Messages.getInstance().getString("Email.ERROR_0014_AUTHENTICATION_FAILED", to), e);
} catch (Throwable e) {
// $NON-NLS-1$
error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e);
}
return false;
}
use of javax.mail.SendFailedException in project OpenAM by OpenRock.
the class EmailPassword method notifyPassword.
/**
* Notifies user when password is changed.
*
* @param user <code>AMIdentity</code> object
* @param password new password
* @param locale user locale
* @throws PWResetException if password cannot be notified
*/
public void notifyPassword(AMIdentity user, String password, Locale locale) throws PWResetException {
ResourceBundle rb = null;
try {
Set<String> set = user.getAttribute(model.getMailAttribute(user.getRealm()));
Set<String> localeSet = user.getAttribute(Constants.USER_LOCALE_ATTR);
if (localeSet == null || localeSet.isEmpty()) {
userLocale = locale;
} else {
String localeStr = localeSet.iterator().next();
userLocale = com.sun.identity.shared.locale.Locale.getLocale(localeStr);
}
rb = PWResetResBundleCacher.getBundle(bundleName, userLocale);
if (set == null || set.isEmpty()) {
model.debugWarning("There is no email address for this user.");
throw new PWResetException(rb.getString("noEmail.message"));
} else {
String emailAddress = set.iterator().next();
sendEmailToUser(emailAddress, password);
}
} catch (SSOException e) {
model.debugWarning("EmailPassword.notifyPassword", e);
throw new PWResetException(e);
} catch (IdRepoException e) {
model.debugWarning("EmailPassword.notifyPassword", e);
throw new PWResetException(e);
} catch (SendFailedException e) {
model.debugWarning("EmailPassword.notifyPassword", e);
throw new PWResetException(rb.getString("sendEmailFailed.message"));
} catch (MessagingException e) {
model.debugWarning("EmailPassword.notifyPassword", e);
throw new PWResetException(e);
}
}
Aggregations