List of usage examples for javax.mail.internet MimeMessage MimeMessage
public MimeMessage(MimeMessage source) throws MessagingException
source
MimeMessage. From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java
/**Builds up a new message from the passed message parts * @param messageType one of the message types definfed in the class AS2Message *///from www. j a v a 2s . c o m public AS2Message createMessage(Partner sender, Partner receiver, AS2Payload[] payloads, int messageType, String messageId) throws Exception { if (messageId == null) { messageId = UniqueId.createMessageId(sender.getAS2Identification(), receiver.getAS2Identification()); } BCCryptoHelper cryptoHelper = new BCCryptoHelper(); AS2MessageInfo info = new AS2MessageInfo(); info.setMessageType(messageType); info.setSenderId(sender.getAS2Identification()); info.setReceiverId(receiver.getAS2Identification()); info.setSenderEMail(sender.getEmail()); info.setMessageId(messageId); info.setDirection(AS2MessageInfo.DIRECTION_OUT); info.setSignType(receiver.getSignType()); info.setEncryptionType(receiver.getEncryptionType()); info.setRequestsSyncMDN(receiver.isSyncMDN()); if (!receiver.isSyncMDN()) { info.setAsyncMDNURL(sender.getMdnURL()); } info.setSubject(receiver.getSubject()); try { info.setSenderHost(InetAddress.getLocalHost().getCanonicalHostName()); } catch (UnknownHostException e) { //nop } //create message object to return AS2Message message = new AS2Message(info); //stores all the available body parts that have been prepared List<MimeBodyPart> contentPartList = new ArrayList<MimeBodyPart>(); for (AS2Payload as2Payload : payloads) { //add payload message.addPayload(as2Payload); if (this.runtimeConnection != null) { MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection); messageAccess.initializeOrUpdateMessage(info); } //no MIME message: single payload, unsigned, no CEM if (info.getSignType() == AS2Message.SIGNATURE_NONE && payloads.length == 1 && info.getMessageType() != AS2Message.MESSAGETYPE_CEM) { return (this.createMessageNoMIME(message, receiver)); } //MIME message MimeBodyPart bodyPart = new MimeBodyPart(); String contentType = null; if (as2Payload.getContentType() == null) { contentType = receiver.getContentType(); } else { contentType = as2Payload.getContentType(); } bodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(as2Payload.getData(), contentType))); bodyPart.addHeader("Content-Type", contentType); if (as2Payload.getContentId() != null) { bodyPart.addHeader("Content-ID", as2Payload.getContentId()); } if (receiver.getContentTransferEncoding() == AS2Message.CONTENT_TRANSFER_ENCODING_BASE64) { bodyPart.addHeader("Content-Transfer-Encoding", "base64"); } else { bodyPart.addHeader("Content-Transfer-Encoding", "binary"); } //prepare filename to not violate the MIME header rules if (as2Payload.getOriginalFilename() == null) { as2Payload.setOriginalFilename(new File(as2Payload.getPayloadFilename()).getName()); } String newFilename = as2Payload.getOriginalFilename().replace(' ', '_'); newFilename = newFilename.replace('@', '_'); newFilename = newFilename.replace(':', '_'); newFilename = newFilename.replace(';', '_'); newFilename = newFilename.replace('(', '_'); newFilename = newFilename.replace(')', '_'); bodyPart.addHeader("Content-Disposition", "attachment; filename=" + newFilename); contentPartList.add(bodyPart); } Part contentPart = null; //sigle attachment? No CEM? Every CEM is in a multipart/related container if (contentPartList.size() == 1 && info.getMessageType() != AS2Message.MESSAGETYPE_CEM) { contentPart = contentPartList.get(0); } else { //build up a new MimeMultipart container for the multiple attachments, content-type //is "multipart/related" MimeMultipart multipart = null; //CEM messages are always in a multipart container (even the response which contains only a single //payload) with the subtype "application/ediint-cert-exchange+xml". if (info.getMessageType() == AS2Message.MESSAGETYPE_CEM) { multipart = new MimeMultipart("related; type=\"application/ediint-cert-exchange+xml\""); } else { multipart = new MimeMultipart("related"); } for (MimeBodyPart bodyPart : contentPartList) { multipart.addBodyPart(bodyPart); } contentPart = new MimeMessage(Session.getInstance(System.getProperties(), null)); contentPart.setContent(multipart, multipart.getContentType()); ((MimeMessage) contentPart).saveChanges(); } //should the content be compressed and enwrapped or just enwrapped? if (receiver.getCompressionType() == AS2Message.COMPRESSION_ZLIB) { info.setCompressionType(AS2Message.COMPRESSION_ZLIB); int uncompressedSize = contentPart.getSize(); contentPart = this.compressPayload(receiver, contentPart); int compressedSize = contentPart.getSize(); //sometimes size() is unable to determine the size of the compressed body part and will return -1. Dont log the //compression ratio in this case. if (uncompressedSize == -1 || compressedSize == -1) { if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("message.compressed.unknownratio", new Object[] { info.getMessageId() }), info); } } else { if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("message.compressed", new Object[] { info.getMessageId(), AS2Tools.getDataSizeDisplay(uncompressedSize), AS2Tools.getDataSizeDisplay(compressedSize) }), info); } } } //compute content mic. Try to use sign digest as hash alg. For unsigned messages take sha-1 String digestOID = null; if (info.getSignType() == AS2Message.SIGNATURE_MD5) { digestOID = cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_MD5); } else { digestOID = cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_SHA1); } String mic = cryptoHelper.calculateMIC(contentPart, digestOID); if (info.getSignType() == AS2Message.SIGNATURE_MD5) { info.setReceivedContentMIC(mic + ", md5"); } else { info.setReceivedContentMIC(mic + ", sha1"); } this.enwrappInMessageAndSign(message, contentPart, sender, receiver); //encryption requested for the receiver? if (info.getEncryptionType() != AS2Message.ENCRYPTION_NONE) { String cryptAlias = this.encryptionCertManager .getAliasByFingerprint(receiver.getCryptFingerprintSHA1()); this.encryptDataToMessage(message, cryptAlias, info.getEncryptionType(), receiver); } else { message.setRawData(message.getDecryptedRawData()); if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("message.notencrypted", new Object[] { info.getMessageId() }), info); } } return (message); }
From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java
@Test public void testProcessUnauthorizedEmailSimpleText() throws MessagingException, IOException { MessageListener mockListener1 = mock(MessageListener.class); when(mockListener1.getComponentId()).thenReturn("componentId"); when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.FALSE); MessageListener mockListener2 = mock(MessageListener.class); messageChecker.addMessageListener(mockListener1); messageChecker.addMessageListener(mockListener2); Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2); listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1); listenersByEmail.put("theflanders@silverpeas.com", mockListener2); MimeMessage mail = new MimeMessage(messageChecker.getMailSession()); InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com"); InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Simple text Email test"); mail.setText(textEmailContent);//from w ww. ja v a 2s.co m Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>(); messageChecker.processEmail(mail, events, listenersByEmail); assertNotNull(events); assertEquals(1, events.size()); assertNull(events.get(mockListener2)); MessageEvent event = events.get(mockListener1); assertNotNull(event); assertNotNull(event.getMessages()); assertEquals(0, event.getMessages().size()); verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com"); }
From source file:com.clustercontrol.notify.util.SendMail.java
public void sendMail(String[] toAddressStr, String[] ccAddressStr, String[] bccAddressStr, String subject, String content) throws MessagingException, UnsupportedEncodingException { if (toAddressStr == null || toAddressStr.length <= 0) { // ??//from w w w . j a v a2s . com return; } /* * https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html */ Properties _properties = new Properties(); _properties.setProperty("mail.debug", Boolean.toString(HinemosPropertyUtil.getHinemosPropertyBool("mail.debug", false))); _properties.setProperty("mail.store.protocol", HinemosPropertyUtil.getHinemosPropertyStr("mail.store.protocol", "pop3")); String protocol = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.protocol", "smtp"); _properties.setProperty("mail.transport.protocol", protocol); _properties.put("mail.smtp.socketFactory", javax.net.SocketFactory.getDefault()); _properties.put("mail.smtp.ssl.socketFactory", javax.net.ssl.SSLSocketFactory.getDefault()); setProperties(_properties, "mail." + protocol + ".user", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".connectiontimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".timeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".writetimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".from", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localhost", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localaddress", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localport", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".ehlo", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.login.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.plain.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.digest-md5.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.domain", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.ntlm.flags", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".submitter", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.notify", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.ret", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".allow8bitmime", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sendpartial", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.authorizationid", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.realm", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.usecanonicalhostname", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".quitwait", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".reportsuccess", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socketFactory.fallback", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".starttls.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".starttls.required", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socks.host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socks.port", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".mailextension", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".userset", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".noop.strict", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.checkserveridentity", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.trust", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail.smtp.ssl.protocols", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.ciphersuites", HinemosPropertyTypeConstant.TYPE_STRING); /** * ?DB?? */ String _loginUser = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.user", "nobody"); String _loginPassword = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.password", "password"); String _fromAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.address", "admin@hinemos.com"); String _fromPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.personal.name", "Hinemos Admin"); _fromPersonalName = convertNativeToAscii(_fromPersonalName); String _replyToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.to.address", "admin@hinemos.com"); String _replyToPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.personal.name", "Hinemos Admin"); _replyToPersonalName = convertNativeToAscii(_replyToPersonalName); String _errorsToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.errors.to.address", "admin@hinemos.com"); int _transportTries = HinemosPropertyUtil.getHinemosPropertyNum("mail.transport.tries", Long.valueOf(1)) .intValue(); int _transportTriesInterval = HinemosPropertyUtil .getHinemosPropertyNum("mail.transport.tries.interval", Long.valueOf(10000)).intValue(); String _charsetAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.address", _charsetAddressDefault); String _charsetSubject = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.subject", _charsetSubjectDefault); String _charsetContent = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.content", _charsetContentDefault); m_log.debug("initialized mail sender : from_address = " + _fromAddress + ", From = " + _fromPersonalName + " <" + _replyToAddress + ">" + ", Reply-To = " + _replyToPersonalName + " <" + _replyToAddress + ">" + ", Errors-To = " + _errorsToAddress + ", tries = " + _transportTries + ", tries-interval = " + _transportTriesInterval + ", Charset [address:subject:content] = [" + _charsetAddress + ":" + _charsetSubject + ":" + _charsetContent + "]"); // JavaMail Session Session session = Session.getInstance(_properties); Message mineMsg = new MimeMessage(session); // ????? if (_fromAddress != null && _fromPersonalName != null) { mineMsg.setFrom(new InternetAddress(_fromAddress, _fromPersonalName, _charsetAddress)); } else if (_fromAddress != null && _fromPersonalName == null) { mineMsg.setFrom(new InternetAddress(_fromAddress)); } // REPLY-TO if (_replyToAddress != null && _replyToPersonalName != null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress, _replyToPersonalName, _charsetAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } else if (_replyToAddress != null && _replyToPersonalName == null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } // ERRORS-TO if (_errorsToAddress != null) { mineMsg.setHeader("Errors-To", _errorsToAddress); } // ? // TO InternetAddress[] toAddress = this.getAddress(toAddressStr); if (toAddress != null && toAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.TO, toAddress); } else { return; // TO? } // CC if (ccAddressStr != null) { InternetAddress[] ccAddress = this.getAddress(ccAddressStr); if (ccAddress != null && ccAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.CC, ccAddress); } } // BCC if (bccAddressStr != null) { InternetAddress[] bccAddress = this.getAddress(bccAddressStr); if (bccAddress != null && bccAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.BCC, bccAddress); } } String message = "TO=" + Arrays.asList(toAddressStr); if (ccAddressStr != null) { message += ", CC=" + Arrays.asList(ccAddressStr); } if (bccAddressStr != null) { message += ", BCC=" + Arrays.asList(bccAddressStr); } m_log.debug(message); // ??? mineMsg.setSubject(MimeUtility.encodeText(subject, _charsetSubject, "B")); // ? mineMsg.setContent(content, "text/plain; charset=" + _charsetContent); // ? mineMsg.setSentDate(HinemosTime.getDateInstance()); // ???true?????? for (int i = 0; i < _transportTries; i++) { Transport transport = null; try { // ? transport = session.getTransport(); boolean flag = HinemosPropertyUtil.getHinemosPropertyBool("mail." + protocol + ".auth", false); if (flag) { transport.connect(_loginUser, _loginPassword); } else { transport.connect(); } transport.sendMessage(mineMsg, mineMsg.getAllRecipients()); break; } catch (AuthenticationFailedException e) { throw e; } catch (SMTPAddressFailedException e) { throw e; } catch (MessagingException me) { //_transportTries?sleep??? if (i < (_transportTries - 1)) { m_log.info("sendMail() : retry sendmail. " + me.getMessage()); try { Thread.sleep(_transportTriesInterval); } catch (InterruptedException e) { } //_transportTries??INTERNAL????Exceptionthrow } else { throw me; } } finally { if (transport != null) { transport.close(); } } } }
From source file:com.enonic.vertical.userservices.OrderHandlerController.java
private void sendMail(String receiverEmail, String receiverName, String senderEmail, String senderName, String subject, String message) throws MessagingException, UnsupportedEncodingException { // smtp server Properties smtpProperties = new Properties(); smtpProperties.put("mail.smtp.host", verticalProperties.getMailSmtpHost()); Session session = Session.getDefaultInstance(smtpProperties, null); // create message Message msg = new MimeMessage(session); // set from address if (senderEmail != null && !senderEmail.equals("")) { InternetAddress addressFrom = new InternetAddress(senderEmail); if (senderName != null && !senderName.equals("")) { addressFrom.setPersonal(senderName); }/* ww w. jav a2 s.com*/ msg.setFrom(addressFrom); } // set to address InternetAddress addressTo = new InternetAddress(receiverEmail); if (receiverName != null) { addressTo.setPersonal(receiverName); } msg.setRecipient(Message.RecipientType.TO, addressTo); // Setting subject and content type msg.setSubject(subject); message = RegexpUtil.substituteAll("(\\\\n)", "\n", message); msg.setContent(message, "text/plain; charset=UTF-8"); // send message Transport.send(msg); }
From source file:org.protocoderrunner.apprunner.api.PNetwork.java
@ProtocoderScript @APIMethod(description = "Send an E-mail. It requires passing a EmailConf object", example = "") @APIParam(params = { "url", "function(data)" }) public void sendEmail(String from, String to, String subject, String text, final EmailConf emailSettings) throws AddressException, MessagingException { if (emailSettings == null) { return;/* w w w . j a v a2 s.c om*/ } // final String host = "smtp.gmail.com"; // final String address = "@gmail.com"; // final String pass = ""; Multipart multiPart; String finalString = ""; Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable", emailSettings.ttl); props.put("mail.smtp.host", emailSettings.host); props.put("mail.smtp.user", emailSettings.user); props.put("mail.smtp.password", emailSettings.password); props.put("mail.smtp.port", emailSettings.port); props.put("mail.smtp.auth", emailSettings.auth); Log.i("Check", "done pops"); final Session session = Session.getDefaultInstance(props, null); DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain")); final MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setDataHandler(handler); Log.i("Check", "done sessions"); multiPart = new MimeMultipart(); InternetAddress toAddress; toAddress = new InternetAddress(to); message.addRecipient(Message.RecipientType.TO, toAddress); Log.i("Check", "added recipient"); message.setSubject(subject); message.setContent(multiPart); message.setText(text); Thread t = new Thread(new Runnable() { @Override public void run() { try { MLog.i("check", "transport"); Transport transport = session.getTransport("smtp"); MLog.i("check", "connecting"); transport.connect(emailSettings.host, emailSettings.user, emailSettings.password); MLog.i("check", "wana send"); transport.sendMessage(message, message.getAllRecipients()); transport.close(); MLog.i("check", "sent"); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } }); t.start(); }
From source file:com.clustercontrol.jobmanagement.util.SendApprovalMail.java
/** * ????//from w ww . j av a2 s .c o m * @param toAddressStr * ?To * @param ccAddressStr * ?Cc * @param subject * ?? * @param content * * @throws MessagingException * @throws UnsupportedEncodingException */ public void sendMail(String[] toAddressStr, String[] ccAddressStr, String subject, String content) throws MessagingException, UnsupportedEncodingException { if (toAddressStr == null || toAddressStr.length <= 0) { // ?? return; } /* * https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html */ Properties _properties = new Properties(); _properties.setProperty("mail.debug", Boolean.toString(HinemosPropertyUtil.getHinemosPropertyBool("mail.debug", false))); _properties.setProperty("mail.store.protocol", HinemosPropertyUtil.getHinemosPropertyStr("mail.store.protocol", "pop3")); String protocol = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.protocol", "smtp"); _properties.setProperty("mail.transport.protocol", protocol); _properties.put("mail.smtp.socketFactory", javax.net.SocketFactory.getDefault()); _properties.put("mail.smtp.ssl.socketFactory", javax.net.ssl.SSLSocketFactory.getDefault()); setProperties(_properties, "mail." + protocol + ".user", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".connectiontimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".timeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".writetimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".from", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localhost", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localaddress", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localport", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".ehlo", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.login.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.plain.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.digest-md5.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.domain", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.ntlm.flags", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".submitter", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.notify", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.ret", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".allow8bitmime", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sendpartial", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.authorizationid", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.realm", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.usecanonicalhostname", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".quitwait", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".reportsuccess", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socketFactory.fallback", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".starttls.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".starttls.required", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socks.host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socks.port", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".mailextension", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".userset", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".noop.strict", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.checkserveridentity", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.trust", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail.smtp.ssl.protocols", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.ciphersuites", HinemosPropertyTypeConstant.TYPE_STRING); /** * ?DB?? */ String _loginUser = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.user", "nobody"); String _loginPassword = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.password", "password"); String _fromAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.address", "admin@hinemos.com"); String _fromPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.personal.name", "Hinemos Admin"); _fromPersonalName = convertNativeToAscii(_fromPersonalName); String _replyToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.to.address", "admin@hinemos.com"); String _replyToPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.personal.name", "Hinemos Admin"); _replyToPersonalName = convertNativeToAscii(_replyToPersonalName); String _errorsToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.errors.to.address", "admin@hinemos.com"); int _transportTries = HinemosPropertyUtil.getHinemosPropertyNum("mail.transport.tries", Long.valueOf(1)) .intValue(); int _transportTriesInterval = HinemosPropertyUtil .getHinemosPropertyNum("mail.transport.tries.interval", Long.valueOf(10000)).intValue(); String _charsetAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.address", _charsetAddressDefault); String _charsetSubject = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.subject", _charsetSubjectDefault); String _charsetContent = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.content", _charsetContentDefault); m_log.debug("initialized mail sender : from_address = " + _fromAddress + ", From = " + _fromPersonalName + " <" + _replyToAddress + ">" + ", Reply-To = " + _replyToPersonalName + " <" + _replyToAddress + ">" + ", Errors-To = " + _errorsToAddress + ", tries = " + _transportTries + ", tries-interval = " + _transportTriesInterval + ", Charset [address:subject:content] = [" + _charsetAddress + ":" + _charsetSubject + ":" + _charsetContent + "]"); // JavaMail Session Session session = Session.getInstance(_properties); Message mineMsg = new MimeMessage(session); // ????? if (_fromAddress != null && _fromPersonalName != null) { mineMsg.setFrom(new InternetAddress(_fromAddress, _fromPersonalName, _charsetAddress)); } else if (_fromAddress != null && _fromPersonalName == null) { mineMsg.setFrom(new InternetAddress(_fromAddress)); } // REPLY-TO if (_replyToAddress != null && _replyToPersonalName != null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress, _replyToPersonalName, _charsetAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } else if (_replyToAddress != null && _replyToPersonalName == null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } // ERRORS-TO if (_errorsToAddress != null) { mineMsg.setHeader("Errors-To", _errorsToAddress); } // ? // TO InternetAddress[] toAddress = this.getAddress(toAddressStr); if (toAddress != null && toAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.TO, toAddress); } else { return; // TO? } // CC if (ccAddressStr != null) { InternetAddress[] ccAddress = this.getAddress(ccAddressStr); if (ccAddress != null && ccAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.CC, ccAddress); } } String message = "TO=" + Arrays.asList(toAddressStr); if (ccAddressStr != null) { message += ", CC=" + Arrays.asList(ccAddressStr); } m_log.debug(message); // ??? mineMsg.setSubject(MimeUtility.encodeText(subject, _charsetSubject, "B")); // ? mineMsg.setContent(content, "text/plain; charset=" + _charsetContent); // ? mineMsg.setSentDate(HinemosTime.getDateInstance()); // ???true?????? for (int i = 0; i < _transportTries; i++) { Transport transport = null; try { // ? transport = session.getTransport(); boolean flag = HinemosPropertyUtil.getHinemosPropertyBool("mail." + protocol + ".auth", false); if (flag) { transport.connect(_loginUser, _loginPassword); } else { transport.connect(); } transport.sendMessage(mineMsg, mineMsg.getAllRecipients()); break; } catch (AuthenticationFailedException e) { throw e; } catch (SMTPAddressFailedException e) { throw e; } catch (MessagingException me) { //_transportTries?sleep??? if (i < (_transportTries - 1)) { m_log.info("sendMail() : retry sendmail. " + me.getMessage()); try { Thread.sleep(_transportTriesInterval); } catch (InterruptedException e) { } //_transportTries??INTERNAL????Exceptionthrow } else { throw me; } } finally { if (transport != null) { transport.close(); } } } }
From source file:be.ibridge.kettle.job.entry.mail.JobEntryMail.java
public Result execute(Result result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); File masterZipfile = null;/*w w w . java 2 s .c o m*/ // Send an e-mail... // create some properties and get the default Session Properties props = new Properties(); if (Const.isEmpty(server)) { log.logError(toString(), "Unable to send the mail because the mail-server (SMTP host) is not specified"); result.setNrErrors(1L); result.setResult(false); return result; } String protocol = "smtp"; if (usingSecureAuthentication) { protocol = "smtps"; } props.put("mail." + protocol + ".host", StringUtil.environmentSubstitute(server)); if (!Const.isEmpty(port)) props.put("mail." + protocol + ".port", StringUtil.environmentSubstitute(port)); boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG; if (debug) props.put("mail.debug", "true"); if (usingAuthentication) { props.put("mail." + protocol + ".auth", "true"); /* authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, "")) ); } }; */ } Session session = Session.getInstance(props); session.setDebug(debug); try { // create a message Message msg = new MimeMessage(session); String email_address = StringUtil.environmentSubstitute(replyAddress); if (!Const.isEmpty(email_address)) { msg.setFrom(new InternetAddress(email_address)); } else { throw new MessagingException("reply e-mail address is not filled in"); } // Split the mail-address: space separated String destinations[] = StringUtil.environmentSubstitute(destination).split(" "); InternetAddress[] address = new InternetAddress[destinations.length]; for (int i = 0; i < destinations.length; i++) address[i] = new InternetAddress(destinations[i]); msg.setRecipients(Message.RecipientType.TO, address); if (!Const.isEmpty(destinationCc)) { // Split the mail-address Cc: space separated String destinationsCc[] = StringUtil.environmentSubstitute(destinationCc).split(" "); InternetAddress[] addressCc = new InternetAddress[destinationsCc.length]; for (int i = 0; i < destinationsCc.length; i++) addressCc[i] = new InternetAddress(destinationsCc[i]); msg.setRecipients(Message.RecipientType.CC, addressCc); } if (!Const.isEmpty(destinationBCc)) { // Split the mail-address BCc: space separated String destinationsBCc[] = StringUtil.environmentSubstitute(destinationBCc).split(" "); InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length]; for (int i = 0; i < destinationsBCc.length; i++) addressBCc[i] = new InternetAddress(destinationsBCc[i]); msg.setRecipients(Message.RecipientType.BCC, addressBCc); } msg.setSubject(StringUtil.environmentSubstitute(subject)); msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); if (comment != null) { messageText.append(StringUtil.environmentSubstitute(comment)).append(Const.CR).append(Const.CR); } if (!onlySendComment) { messageText.append("Job:").append(Const.CR); messageText.append("-----").append(Const.CR); messageText.append("Name : ").append(parentJob.getJobMeta().getName()).append(Const.CR); messageText.append("Directory : ").append(parentJob.getJobMeta().getDirectory()).append(Const.CR); messageText.append("JobEntry : ").append(getName()).append(Const.CR); messageText.append(Const.CR); } if (includeDate) { Value date = new Value("date", new Date()); messageText.append("Message date: ").append(date.toString()).append(Const.CR).append(Const.CR); } if (!onlySendComment && result != null) { messageText.append("Previous result:").append(Const.CR); messageText.append("-----------------").append(Const.CR); messageText.append("Job entry nr : ").append(result.getEntryNr()).append(Const.CR); messageText.append("Errors : ").append(result.getNrErrors()).append(Const.CR); messageText.append("Lines read : ").append(result.getNrLinesRead()).append(Const.CR); messageText.append("Lines written : ").append(result.getNrLinesWritten()).append(Const.CR); messageText.append("Lines input : ").append(result.getNrLinesInput()).append(Const.CR); messageText.append("Lines output : ").append(result.getNrLinesOutput()).append(Const.CR); messageText.append("Lines updated : ").append(result.getNrLinesUpdated()).append(Const.CR); messageText.append("Script exit status : ").append(result.getExitStatus()).append(Const.CR); messageText.append("Result : ").append(result.getResult()).append(Const.CR); messageText.append(Const.CR); } if (!onlySendComment && (!Const.isEmpty(StringUtil.environmentSubstitute(contactPerson)) || !Const.isEmpty(StringUtil.environmentSubstitute(contactPhone)))) { messageText.append("Contact information :").append(Const.CR); messageText.append("---------------------").append(Const.CR); messageText.append("Person to contact : ").append(StringUtil.environmentSubstitute(contactPerson)) .append(Const.CR); messageText.append("Telephone number : ").append(StringUtil.environmentSubstitute(contactPhone)) .append(Const.CR); messageText.append(Const.CR); } // Include the path to this job entry... if (!onlySendComment) { JobTracker jobTracker = parentJob.getJobTracker(); if (jobTracker != null) { messageText.append("Path to this job entry:").append(Const.CR); messageText.append("------------------------").append(Const.CR); addBacktracking(jobTracker, messageText); } } Multipart parts = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); // put the text in the // 1st part part1.setText(messageText.toString()); parts.addBodyPart(part1); if (includingFiles && result != null) { List resultFiles = result.getResultFilesList(); if (resultFiles != null && resultFiles.size() > 0) { if (!zipFiles) { // Add all files to the message... // for (Iterator iter = resultFiles.iterator(); iter.hasNext();) { ResultFile resultFile = (ResultFile) iter.next(); FileObject file = resultFile.getFile(); if (file != null && file.exists()) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) found = true; } if (found) { // create a data source MimeBodyPart files = new MimeBodyPart(); URLDataSource fds = new URLDataSource(file.getURL()); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in the data source files.setFileName(fds.getName()); // add the part with the file in the BodyPart(); parts.addBodyPart(files); log.logBasic(toString(), "Added file '" + fds.getName() + "' to the mail message."); } } } } else { // create a single ZIP archive of all files masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR + StringUtil.environmentSubstitute(zipFilename)); ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile)); for (Iterator iter = resultFiles.iterator(); iter.hasNext();) { ResultFile resultFile = (ResultFile) iter.next(); boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) found = true; } if (found) { FileObject file = resultFile.getFile(); ZipEntry zipEntry = new ZipEntry(file.getName().getURI()); zipOutputStream.putNextEntry(zipEntry); // Now put the content of this file into this archive... BufferedInputStream inputStream = new BufferedInputStream( file.getContent().getInputStream()); int c; while ((c = inputStream.read()) >= 0) { zipOutputStream.write(c); } inputStream.close(); zipOutputStream.closeEntry(); log.logBasic(toString(), "Added file '" + file.getName().getURI() + "' to the mail message in a zip archive."); } } } catch (Exception e) { log.logError(toString(), "Error zipping attachement files into file [" + masterZipfile.getPath() + "] : " + e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); } finally { if (zipOutputStream != null) { try { zipOutputStream.finish(); zipOutputStream.close(); } catch (IOException e) { log.logError(toString(), "Unable to close attachement zip file archive : " + e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); } } } // Now attach the master zip file to the message. if (result.getNrErrors() == 0) { // create a data source MimeBodyPart files = new MimeBodyPart(); FileDataSource fds = new FileDataSource(masterZipfile); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in th e data source files.setFileName(fds.getName()); // add the part with the file in the BodyPart(); parts.addBodyPart(files); } } } } msg.setContent(parts); Transport transport = null; try { transport = session.getTransport(protocol); if (usingAuthentication) { if (!Const.isEmpty(port)) { transport.connect(StringUtil.environmentSubstitute(Const.NVL(server, "")), Integer.parseInt(StringUtil.environmentSubstitute(Const.NVL(port, ""))), StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, ""))); } else { transport.connect(StringUtil.environmentSubstitute(Const.NVL(server, "")), StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, ""))); } } else { transport.connect(); } transport.sendMessage(msg, msg.getAllRecipients()); } finally { if (transport != null) transport.close(); } } catch (IOException e) { log.logError(toString(), "Problem while sending message: " + e.toString()); result.setNrErrors(1); } catch (MessagingException mex) { log.logError(toString(), "Problem while sending message: " + mex.toString()); result.setNrErrors(1); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { log.logError(toString(), " ** Invalid Addresses"); for (int i = 0; i < invalid.length; i++) { log.logError(toString(), " " + invalid[i]); result.setNrErrors(1); } } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { log.logError(toString(), " ** ValidUnsent Addresses"); for (int i = 0; i < validUnsent.length; i++) { log.logError(toString(), " " + validUnsent[i]); result.setNrErrors(1); } } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { //System.out.println(" ** ValidSent Addresses"); for (int i = 0; i < validSent.length; i++) { log.logError(toString(), " " + validSent[i]); result.setNrErrors(1); } } } if (ex instanceof MessagingException) { ex = ((MessagingException) ex).getNextException(); } else { ex = null; } } while (ex != null); } finally { if (masterZipfile != null && masterZipfile.exists()) { masterZipfile.delete(); } } if (result.getNrErrors() > 0) { result.setResult(false); } else { result.setResult(true); } return result; }
From source file:com.emc.kibana.emailer.KibanaEmailer.java
private static void sendFileEmail(String security) { final String username = smtpUsername; final String password = smtpPassword; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", smtpHost); if (security.equals(SMTP_SECURITY_TLS)) { properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", smtpHost); properties.put("mail.smtp.port", smtpPort); } else if (security.equals(SMTP_SECURITY_SSL)) { properties.put("mail.smtp.socketFactory.port", smtpPort); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.port", smtpPort); }/*w w w .j a va 2 s. c o m*/ Session session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(sourceAddress)); // Set To: header field of the header. for (String destinationAddress : destinationAddressList) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(destinationAddress)); } // Set Subject: header field message.setSubject(mailTitle); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); StringBuffer bodyBuffer = new StringBuffer(mailBody); if (!kibanaUrls.isEmpty()) { bodyBuffer.append("\n\n"); } // Add urls info to e-mail for (Map<String, String> kibanaUrl : kibanaUrls) { // Add urls to e-mail String urlName = kibanaUrl.get(NAME_KEY); String reportUrl = kibanaUrl.get(URL_KEY); if (urlName != null && reportUrl != null) { bodyBuffer.append("- ").append(urlName).append(": ").append(reportUrl).append("\n\n\n"); } } // Fill the message messageBodyPart.setText(bodyBuffer.toString()); // Create a multipart message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachments for (Map<String, String> kibanaScreenCapture : kibanaScreenCaptures) { messageBodyPart = new MimeBodyPart(); String absoluteFilename = kibanaScreenCapture.get(ABSOLUE_FILE_NAME_KEY); String filename = kibanaScreenCapture.get(FILE_NAME_KEY); DataSource source = new FileDataSource(absoluteFilename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); } // Send the complete message parts message.setContent(multipart); // Send message Transport.send(message); logger.info("Sent mail message successfully"); } catch (MessagingException mex) { throw new RuntimeException(mex); } }
From source file:com.netflix.ice.basic.BasicWeeklyCostEmailService.java
private void sendEmail(boolean test, AmazonSimpleEmailServiceClient emailService, String email, List<ApplicationGroup> appGroups) throws IOException, MessagingException { StringBuilder body = new StringBuilder(); body.append(// ww w. j a v a2 s. c om "<html><head><style type=\"text/css\">a:link, a:visited{color:#006DBA;}a:link, a:visited, a:hover {\n" + "text-decoration: none;\n" + "}\n" + "body {\n" + "color: #333;\n" + "}" + "</style></head>"); List<MimeBodyPart> mimeBodyParts = Lists.newArrayList(); int index = 0; String subject = ""; for (ApplicationGroup appGroup : appGroups) { boolean hasData = false; for (String prodName : appGroup.data.keySet()) { if (config.productService.getProductByName(prodName) == null) continue; hasData = appGroup.data.get(prodName) != null && appGroup.data.get(prodName).size() > 0; if (hasData) break; } if (!hasData) continue; try { MimeBodyPart mimeBodyPart = constructEmail(index, appGroup, body); index++; if (mimeBodyPart != null) { mimeBodyParts.add(mimeBodyPart); subject = subject + (subject.length() > 0 ? ", " : "") + appGroup.getDisplayName(); } } catch (Exception e) { logger.error("Error contructing email", e); } } body.append("</html>"); if (mimeBodyParts.size() == 0) return; DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0); subject = String.format("%s Weekly AWS Costs (%s - %s)", subject, formatter.print(end.minusWeeks(1)), formatter.print(end)); String toEmail = test ? testEmail : email; Session session = Session.getInstance(new Properties()); MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setSubject(subject); mimeMessage.setRecipients(javax.mail.Message.RecipientType.TO, toEmail); if (!test && !StringUtils.isEmpty(bccEmail)) { mimeMessage.addRecipients(Message.RecipientType.BCC, bccEmail); } MimeMultipart mimeMultipart = new MimeMultipart(); BodyPart p = new MimeBodyPart(); p.setContent(body.toString(), "text/html"); mimeMultipart.addBodyPart(p); for (MimeBodyPart mimeBodyPart : mimeBodyParts) mimeMultipart.addBodyPart(mimeBodyPart); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); mimeMessage.setContent(mimeMultipart); mimeMessage.writeTo(outputStream); RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray())); SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage); rawEmailRequest.setDestinations(Lists.<String>newArrayList(toEmail)); rawEmailRequest.setSource(fromEmail); logger.info("sending email to " + toEmail + " " + body.toString()); emailService.sendRawEmail(rawEmailRequest); }
From source file:com.panet.imeta.trans.steps.mail.Mail.java
public void sendMail(Object[] r, String server, String port, String senderAddress, String senderName, String destination, String destinationCc, String destinationBCc, String contactPerson, String contactPhone, String authenticationUser, String authenticationPassword, String mailsubject, String comment, String replyToAddresses) throws Exception { // Send an e-mail... // create some properties and get the default Session String protocol = "smtp"; if (meta.isUsingAuthentication()) { if (meta.getSecureConnectionType().equals("TLS")) { // Allow TLS authentication data.props.put("mail.smtp.starttls.enable", "true"); } else {//from w ww. j a v a2 s. c om protocol = "smtps"; // required to get rid of a SSL exception : // nested exception is: // javax.net.ssl.SSLException: Unsupported record version Unknown data.props.put("mail.smtps.quitwait", "false"); } } data.props.put("mail." + protocol + ".host", server); if (!Const.isEmpty(port)) data.props.put("mail." + protocol + ".port", port); boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG; if (debug) data.props.put("mail.debug", "true"); if (meta.isUsingAuthentication()) data.props.put("mail." + protocol + ".auth", "true"); Session session = Session.getInstance(data.props); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); // set message priority if (meta.isUsePriority()) { String priority_int = "1"; if (meta.getPriority().equals("low")) priority_int = "3"; if (meta.getPriority().equals("normal")) priority_int = "2"; msg.setHeader("X-Priority", priority_int); //(String)int between 1= high and 3 = low. msg.setHeader("Importance", meta.getImportance()); //seems to be needed for MS Outlook. //where it returns a string of high /normal /low. } // set Email sender String email_address = senderAddress; if (!Const.isEmpty(email_address)) { // get sender name if (!Const.isEmpty(senderName)) email_address = senderName + '<' + email_address + '>'; msg.setFrom(new InternetAddress(email_address)); } else { throw new MessagingException(Messages.getString("Mail.Error.ReplyEmailNotFilled")); } // Set reply to if (!Const.isEmpty(replyToAddresses)) { // get replay to // Split the mail-address: space separated String[] reply_Address_List = replyToAddresses.split(" "); InternetAddress[] address = new InternetAddress[reply_Address_List.length]; for (int i = 0; i < reply_Address_List.length; i++) address[i] = new InternetAddress(reply_Address_List[i]); // To add the real reply-to msg.setReplyTo(address); } // Split the mail-address: space separated String destinations[] = destination.split(" "); InternetAddress[] address = new InternetAddress[destinations.length]; for (int i = 0; i < destinations.length; i++) address[i] = new InternetAddress(destinations[i]); msg.setRecipients(Message.RecipientType.TO, address); String realdestinationCc = destinationCc; if (!Const.isEmpty(realdestinationCc)) { // Split the mail-address Cc: space separated String destinationsCc[] = realdestinationCc.split(" "); InternetAddress[] addressCc = new InternetAddress[destinationsCc.length]; for (int i = 0; i < destinationsCc.length; i++) addressCc[i] = new InternetAddress(destinationsCc[i]); msg.setRecipients(Message.RecipientType.CC, addressCc); } String realdestinationBCc = destinationBCc; if (!Const.isEmpty(realdestinationBCc)) { // Split the mail-address BCc: space separated String destinationsBCc[] = realdestinationBCc.split(" "); InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length]; for (int i = 0; i < destinationsBCc.length; i++) addressBCc[i] = new InternetAddress(destinationsBCc[i]); msg.setRecipients(Message.RecipientType.BCC, addressBCc); } if (mailsubject != null) msg.setSubject(mailsubject); msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); if (comment != null) messageText.append(comment).append(Const.CR).append(Const.CR); if (meta.getIncludeDate()) messageText.append(Messages.getString("Mail.Log.Comment.MsgDate") + ": ") .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR); if (!meta.isOnlySendComment() && (!Const.isEmpty(contactPerson) || !Const.isEmpty(contactPhone))) { messageText.append(Messages.getString("Mail.Log.Comment.ContactInfo") + " :").append(Const.CR); messageText.append("---------------------").append(Const.CR); messageText.append(Messages.getString("Mail.Log.Comment.PersonToContact") + " : ").append(contactPerson) .append(Const.CR); messageText.append(Messages.getString("Mail.Log.Comment.Tel") + " : ").append(contactPhone) .append(Const.CR); messageText.append(Const.CR); } data.parts = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); // put the text in the // 1st part if (meta.isUseHTML()) { if (!Const.isEmpty(meta.getEncoding())) part1.setContent(messageText.toString(), "text/html; " + "charset=" + meta.getEncoding()); else part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1"); } else part1.setText(messageText.toString()); data.parts.addBodyPart(part1); // attached files if (meta.isDynamicFilename()) setAttachedFilesList(r, log); else setAttachedFilesList(null, log); msg.setContent(data.parts); Transport transport = null; try { transport = session.getTransport(protocol); if (meta.isUsingAuthentication()) { if (!Const.isEmpty(port)) { transport.connect(Const.NVL(server, ""), Integer.parseInt(Const.NVL(port, "")), Const.NVL(authenticationUser, ""), Const.NVL(authenticationPassword, "")); } else { transport.connect(Const.NVL(server, ""), Const.NVL(authenticationUser, ""), Const.NVL(authenticationPassword, "")); } } else { transport.connect(); } transport.sendMessage(msg, msg.getAllRecipients()); } finally { if (transport != null) transport.close(); } }