public void sendMessage (Message oMsg, Address[] aAdrFrom, Address[] aAdrReply, Address[] aAdrTo, Address[] aAdrCc, Address[] aAdrBcc) throws NoSuchProviderException,SendFailedException,ParseException, MessagingException,NullPointerException { oMsg.addFrom(aAdrFrom); if (null==aAdrReply) oMsg.setReplyTo(aAdrReply); else oMsg.setReplyTo(aAdrFrom); if (aAdrTo!=null) oMsg.addRecipients(javax.mail.Message.RecipientType.TO, aAdrTo); if (aAdrCc!=null) oMsg.addRecipients(javax.mail.Message.RecipientType.CC, aAdrCc); if (aAdrBcc!=null) oMsg.addRecipients(javax.mail.Message.RecipientType.BCC, aAdrBcc); oMsg.setSentDate(new java.util.Date()); Transport.send(oMsg); }
@Asynchronous public void sendEmail(String to, Message.RecipientType recipientType, String subject, String body) throws MessagingException, SendFailedException { MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(mailSession.getProperty("mail.from"))); InternetAddress[] address = {new InternetAddress(to)}; message.setRecipients(recipientType, address); message.setSubject(subject); message.setContent(body, "text/html"); // set the timestamp message.setSentDate(new Date()); message.setText(body); try { Transport.send(message); } catch (MessagingException ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } }
/** * Show the error list from the e-mail API if there are errors * * @param parent * @param sfe */ private void showFailedException(SendFailedException sfe) { String error = sfe.getMessage() + "\n"; Address[] ia = sfe.getInvalidAddresses(); if (ia != null) { for (int x = 0; x < ia.length; x++) { error += "Invalid Address: " + ia[x].toString() + "\n"; } } JTextArea ea = new JTextArea(error,6,50); JScrollPane errorScrollPane = new JScrollPane(ea); errorScrollPane.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); errorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); JOptionPane.showMessageDialog(null, errorScrollPane, LangTool.getString("em.titleConfirmation"), JOptionPane.ERROR_MESSAGE); }
private String handleMessagingException(Exception e) { StringBuffer exmess = new StringBuffer(); do { if (e instanceof SendFailedException) { SendFailedException sfex = (SendFailedException)e; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { exmess.append("\n ** Invalid Addresses"); if (invalid != null) { for (int i = 0; i < invalid.length; i++) exmess.append(" " + invalid[i]); } } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { exmess.append("\n ** ValidUnsent Addresses"); if (validUnsent != null) { for (int i = 0; i < validUnsent.length; i++) exmess.append(" "+validUnsent[i]); } } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { exmess.append("\n ** ValidSent Addresses"); if (validSent != null) { for (int i = 0; i < validSent.length; i++) exmess.append(" "+validSent[i]); } } } if (e instanceof MessagingException) e = ((MessagingException)e).getNextException(); else e = null; } while (e != null); return exmess.toString(); }
@Asynchronous public void sendEmails(String listAddrs, String subject, String body) throws MessagingException, SendFailedException { List<String> addrs = Arrays.asList(listAddrs.split("\\s*,\\s*")); boolean first = false; MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(mailSession.getProperty("mail.from"))); message.setSubject(subject); message.setContent(body, "text/html"); message.setSentDate(new Date()); message.setText(body); for (String addr : addrs) { InternetAddress[] address = {new InternetAddress(addr)}; if (first) { message.setRecipients(Message.RecipientType.TO, address); first = false; } else { message.setRecipients(Message.RecipientType.CC, address); } } try { Transport.send(message); } catch (MessagingException ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } }
/** * handles the sendFailedException * <p> * creates a MessageSendStatus which contains a translateable info or error message, and the knowledge if the user can proceed with its action. * * @param e * @throws OLATRuntimeException return MessageSendStatus */ private MessageSendStatus handleSendFailedException(final SendFailedException e) { // get wrapped excpetion MessageSendStatus messageSendStatus = null; final MessagingException me = (MessagingException) e.getNextException(); if (me instanceof AuthenticationFailedException) { messageSendStatus = createAuthenticationFailedMessageSendStatus(); return messageSendStatus; } final String message = me.getMessage(); if (message.startsWith("553")) { messageSendStatus = createInvalidDomainMessageSendStatus(); } else if (message.startsWith("Invalid Addresses")) { messageSendStatus = createInvalidAddressesMessageSendStatus(e.getInvalidAddresses()); } else if (message.startsWith("503 5.0.0")) { messageSendStatus = createNoRecipientMessageSendStatus(); } else if (message.startsWith("Unknown SMTP host")) { messageSendStatus = createUnknownSMTPHost(); } else if (message.startsWith("Could not connect to SMTP host")) { messageSendStatus = createCouldNotConnectToSmtpHostMessageSendStatus(); } else { List<ContactList> emailToContactLists = getTheToContactLists(); String exceptionMessage = ""; for (ContactList contactList : emailToContactLists) { exceptionMessage += contactList.toString(); } throw new OLATRuntimeException(ContactUIModel.class, exceptionMessage, me); } return messageSendStatus; }
private boolean sendEmail(String from, String mailto, String subject, String body) throws AddressException, SendFailedException, MessagingException { if (webappAndMailHelper.isEmailFunctionalityDisabled()) return false; InternetAddress mailFromAddress = new InternetAddress(from); InternetAddress mailToAddress[] = InternetAddress.parse(mailto); MailerResult result = new MailerResult(); MimeMessage msg = webappAndMailHelper.createMessage(mailFromAddress, mailToAddress, null, null, body + footer, subject, null, result); webappAndMailHelper.send(msg, result); //TODO:discuss why is the MailerResult not used here? return true; }
@Test public void testSendWithoutException() { //setup ExceptionHandlingMailSendingTemplate doSendWithoutException = new ExceptionHandlingMailSendingTemplate() { @Override protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException { assertNotNull("emailer was constructed", emailer); return true; } @Override protected MailTemplate getMailTemplate() { return emptyMailTemplate; }; @Override protected List<ContactList> getTheToContactLists() { return theContactLists; } @Override protected Identity getFromIdentity() { return theFromIdentity; } }; //exercise MessageSendStatus sendStatus = doSendWithoutException.send(); //verify assertEquals(MessageSendStatusCode.SUCCESSFULL_SENT_EMAILS, sendStatus.getStatusCode()); assertTrue(sendStatus.getStatusCode().isSuccessfullSentMails()); assertFalse(sendStatus.isSeverityError()); assertFalse(sendStatus.isSeverityWarn()); assertTrue(sendStatus.canProceedWithWorkflow()); }
@Test public void shouldFailWithAddressExcpetion(){ //setup ExceptionHandlingMailSendingTemplate doSendWithAddressException = new ExceptionHandlingMailSendingTemplate() { @Override protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException { assertNotNull("emailer was constructed", emailer); throw new AddressException(); } @Override protected MailTemplate getMailTemplate() { return emptyMailTemplate; }; @Override protected List<ContactList> getTheToContactLists() { return theContactLists; } @Override protected Identity getFromIdentity() { return theFromIdentity; } }; //exercise MessageSendStatus sendStatus = doSendWithAddressException.send(); //verify assertEquals(MessageSendStatusCode.SENDER_OR_RECIPIENTS_NOK_553, sendStatus.getStatusCode()); verifyStatusCodeIndicateAddressExceptionOnly(sendStatus); verifySendStatusIsWarn(sendStatus); assertFalse(sendStatus.canProceedWithWorkflow()); }
@Test public void shouldFailWithSendFailedExceptionWithDomainErrorCode553(){ //setup ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() { @Override protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException { assertNotNull("emailer was constructed", emailer); MessagingException firstInnerException = new SendFailedException("553 some domain error message from the mailsystem"); throw new SendFailedException(BY_OLAT_UNHANDLED_TEXT, firstInnerException); } @Override protected MailTemplate getMailTemplate() { return emptyMailTemplate; }; @Override protected List<ContactList> getTheToContactLists() { return theContactLists; } @Override protected Identity getFromIdentity() { return theFromIdentity; } }; //exercise MessageSendStatus sendStatus = doSendWithSendFailedException.send(); //verify assertEquals(MessageSendStatusCode.SEND_FAILED_DUE_INVALID_DOMAIN_NAME_553, sendStatus.getStatusCode()); verifyStatusCodeIndicateSendFailedOnly(sendStatus); verifySendStatusIsError(sendStatus); assertFalse(sendStatus.canProceedWithWorkflow()); }
@Test public void shouldFailWithSendFailedExceptionWithInvalidAddresses(){ //setup ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() { @Override protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException { assertNotNull("emailer was constructed", emailer); MessagingException firstInnerException = new SendFailedException("Invalid Addresses <followed by a list of invalid addresses>"); throw new SendFailedException(BY_OLAT_UNHANDLED_TEXT, firstInnerException); } @Override protected MailTemplate getMailTemplate() { return emptyMailTemplate; }; @Override protected List<ContactList> getTheToContactLists() { return theContactLists; } @Override protected Identity getFromIdentity() { return theFromIdentity; } }; //exercise MessageSendStatus sendStatus = doSendWithSendFailedException.send(); //verify assertEquals(MessageSendStatusCode.SEND_FAILED_DUE_INVALID_ADDRESSES_550, sendStatus.getStatusCode()); verifyStatusCodeIndicateSendFailedOnly(sendStatus); verifySendStatusIsError(sendStatus); assertFalse(sendStatus.canProceedWithWorkflow()); }
@Test public void shouldFailWithSendFailedExceptionBecauseNoRecipient(){ //setup ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() { @Override protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException { assertNotNull("emailer was constructed", emailer); MessagingException firstInnerException = new SendFailedException("503 5.0.0 .... "); throw new SendFailedException(BY_OLAT_UNHANDLED_TEXT, firstInnerException); } @Override protected MailTemplate getMailTemplate() { return emptyMailTemplate; }; @Override protected List<ContactList> getTheToContactLists() { return theContactLists; } @Override protected Identity getFromIdentity() { return theFromIdentity; } }; //exercise MessageSendStatus sendStatus = doSendWithSendFailedException.send(); //verify assertEquals(MessageSendStatusCode.SEND_FAILED_DUE_NO_RECIPIENTS_503, sendStatus.getStatusCode()); verifyStatusCodeIndicateSendFailedOnly(sendStatus); verifySendStatusIsError(sendStatus); assertFalse(sendStatus.canProceedWithWorkflow()); }
@Test public void shouldFailWithSendFailedExceptionBecauseUnknownSMTPHost(){ //setup ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() { @Override protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException { assertNotNull("emailer was constructed", emailer); MessagingException firstInnerException = new SendFailedException("Unknown SMTP host"); throw new SendFailedException(BY_OLAT_UNHANDLED_TEXT, firstInnerException); } @Override protected MailTemplate getMailTemplate() { return emptyMailTemplate; }; @Override protected List<ContactList> getTheToContactLists() { return theContactLists; } @Override protected Identity getFromIdentity() { return theFromIdentity; } }; //exercise MessageSendStatus sendStatus = doSendWithSendFailedException.send(); //verify assertEquals(MessageSendStatusCode.SEND_FAILED_DUE_UNKNOWN_SMTP_HOST, sendStatus.getStatusCode()); verifyStatusCodeIndicateSendFailedOnly(sendStatus); verifySendStatusIsError(sendStatus); assertTrue(sendStatus.canProceedWithWorkflow()); }
@Test public void shouldFailWithSendFailedExceptionBecauseCouldNotConnectToSMTPHost(){ //setup ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() { @Override protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException { assertNotNull("emailer was constructed", emailer); MessagingException firstInnerException = new SendFailedException("Could not connect to SMTP host"); throw new SendFailedException(BY_OLAT_UNHANDLED_TEXT, firstInnerException); } @Override protected MailTemplate getMailTemplate() { return emptyMailTemplate; }; @Override protected List<ContactList> getTheToContactLists() { return theContactLists; } @Override protected Identity getFromIdentity() { return theFromIdentity; } }; //exercise MessageSendStatus sendStatus = doSendWithSendFailedException.send(); //verify assertEquals(MessageSendStatusCode.SEND_FAILED_DUE_COULD_NOT_CONNECT_TO_SMTP_HOST, sendStatus.getStatusCode()); verifyStatusCodeIndicateSendFailedOnly(sendStatus); verifySendStatusIsError(sendStatus); assertTrue(sendStatus.canProceedWithWorkflow()); }
@Test public void shouldFailWithSendFailedExceptionWithAnAuthenticationFailedException(){ //setup ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() { @Override protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException { assertNotNull("emailer was constructed", emailer); MessagingException firstInnerException = new AuthenticationFailedException("<some authentication failed message from the mailsystem>"); throw new SendFailedException(BY_OLAT_UNHANDLED_TEXT, firstInnerException); } @Override protected MailTemplate getMailTemplate() { return emptyMailTemplate; }; @Override protected List<ContactList> getTheToContactLists() { return theContactLists; } @Override protected Identity getFromIdentity() { return theFromIdentity; } }; //exercise MessageSendStatus sendStatus = doSendWithSendFailedException.send(); //verify assertEquals(MessageSendStatusCode.SMTP_AUTHENTICATION_FAILED, sendStatus.getStatusCode()); verifyStatusCodeIndicateSendFailedOnly(sendStatus); verifySendStatusIsError(sendStatus); assertTrue(sendStatus.canProceedWithWorkflow()); }
@Test public void shouldFailWithOLATRuntimeExceptionWithAnUnhandletSendFailedException(){ //setup ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() { @Override protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException { assertNotNull("emailer was constructed", emailer); MessagingException firstInnerException = new SendFailedException("unhandled sendfail exception"); throw new SendFailedException(BY_OLAT_UNHANDLED_TEXT, firstInnerException); } @Override protected MailTemplate getMailTemplate() { return emptyMailTemplate; }; @Override protected List<ContactList> getTheToContactLists() { return theContactLists; } @Override protected Identity getFromIdentity() { return theFromIdentity; } }; //exercise try{ MessageSendStatus sendStatus = doSendWithSendFailedException.send(); fail("OLATRuntime exception is not thrown."); }catch(OLATRuntimeException ore){ assertNotNull(ore); } }
@Theory public void shouldFailWithErrorWithAnyOtherMessagingException(final MessagingException me){ //setup ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() { @Override protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException { assertNotNull("emailer was constructed", emailer); throw me; } @Override protected MailTemplate getMailTemplate() { return emptyMailTemplate; }; @Override protected List<ContactList> getTheToContactLists() { return theContactLists; } @Override protected Identity getFromIdentity() { return theFromIdentity; } }; //exercise MessageSendStatus sendStatus = doSendWithSendFailedException.send(); //verify assertEquals(MessageSendStatusCode.MAIL_CONTENT_NOK, sendStatus.getStatusCode()); verifyStatusCodeIndicateMessagingExcpetionOnly(sendStatus); verifySendStatusIsWarn(sendStatus); assertFalse(sendStatus.canProceedWithWorkflow()); }
@Test public void testSystemEmailerSetupBySendingAMessageFromAdminToInfo() throws AddressException, SendFailedException, MessagingException{ //Setup //Exercise systemEmailer.sendEmail(ObjectMother.OLATINFO_EMAIL, ObjectMother.AN_EXAMPLE_SUBJECT, ObjectMother.HELLOY_KITTY_THIS_IS_AN_EXAMPLE_BODY); //Verify verify(webappAndMailhelperMockSystemMailer, times(1)).send(any(MimeMessage.class), any(MailerResult.class)); assertEquals("system is mail sender", ObjectMother.OLATADMIN_EMAIL, systemEmailer.mailfrom); }
@Test public void testShouldNotSendAnEmailWithDisabledMailHost() throws AddressException, SendFailedException, MessagingException{ //Setup MailPackageStaticDependenciesWrapper webappAndMailhelperMock = createWebappAndMailhelperWithDisabledMailFunctinality(); Emailer anEmailer = new Emailer(mailTemplateMockForSystemMailer, webappAndMailhelperMock); //Exercise anEmailer.sendEmail(ObjectMother.OLATINFO_EMAIL, ObjectMother.AN_EXAMPLE_SUBJECT, ObjectMother.HELLOY_KITTY_THIS_IS_AN_EXAMPLE_BODY); //Verify verify(webappAndMailhelperMock, never()).send(any(MimeMessage.class), any(MailerResult.class)); }
public void sendMessages() throws MessagingException { Transport transport = null; try { URLName url = new URLName("smtp", host, port, "", username, password); if (session == null) { createSession(); } transport = new com.sun.mail.smtp.SMTPTransport(session, url); transport.connect(host, port, username, password); for (MimeMessage message : messages) { // Attempt to send message, but catch exceptions caused by invalid // addresses so that other messages can continue to be sent. try { transport.sendMessage(message, message.getRecipients(MimeMessage.RecipientType.TO)); } catch (AddressException | SendFailedException ae) { Log.error(ae.getMessage(), ae); } } } finally { if (transport != null) { try { transport.close(); } catch (MessagingException e) { /* ignore */ } } } }
/** * Send a Multipart text message with attached files. FIXME: use prepareMessage method * * @param strRecipientsTo * The list of the main recipients email.Every recipient must be separated by the mail separator defined in config.properties * @param strRecipientsCc * The recipients list of the carbon copies . * @param strRecipientsBcc * The recipients list of the blind carbon copies . * @param strSenderName * The sender name. * @param strSenderEmail * The sender email address. * @param strSubject * The message subject. * @param strMessage * The message. * @param fileAttachements * The list of attached files * @param transport * the smtp transport object * @param session * the smtp session object * @throws AddressException * If invalid address * @throws SendFailedException * If an error occured during sending * @throws MessagingException * If a messaging error occured */ protected static void sendMultipartMessageText( String strRecipientsTo, String strRecipientsCc, String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject, String strMessage, List<FileAttachment> fileAttachements, Transport transport, Session session ) throws MessagingException, AddressException, SendFailedException { Message msg = prepareMessage( strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName, strSenderEmail, strSubject, session ); msg.setHeader( HEADER_NAME, HEADER_VALUE ); // Creation of the root part containing all the elements of the message MimeMultipart multipart = new MimeMultipart( ); // Creation of the html part, the "core" of the message BodyPart msgBodyPart = new MimeBodyPart( ); // msgBodyPart.setContent( strMessage, BODY_PART_MIME_TYPE ); msgBodyPart.setDataHandler( new DataHandler( new ByteArrayDataSource( strMessage, AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_PLAIN ) + AppPropertiesService.getProperty( PROPERTY_CHARSET ) ) ) ); multipart.addBodyPart( msgBodyPart ); // add File Attachement if ( fileAttachements != null ) { for ( FileAttachment fileAttachement : fileAttachements ) { String strFileName = fileAttachement.getFileName( ); byte [ ] bContentFile = fileAttachement.getData( ); String strContentType = fileAttachement.getType( ); ByteArrayDataSource dataSource = new ByteArrayDataSource( bContentFile, strContentType ); msgBodyPart = new MimeBodyPart( ); msgBodyPart.setDataHandler( new DataHandler( dataSource ) ); msgBodyPart.setFileName( strFileName ); msgBodyPart.setDisposition( CONSTANT_DISPOSITION_ATTACHMENT ); multipart.addBodyPart( msgBodyPart ); } } msg.setContent( multipart ); sendMessage( msg, transport ); }
/** * @param mex */ private static void handleEMailError(MessagingException mex) { mex.printStackTrace(); System.out.println(); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { System.out.println(" ** Invalid Addresses"); for (int i = 0; i < invalid.length; i++) System.out.println(" " + invalid[i]); } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { System.out.println(" ** ValidUnsent Addresses"); for (int i = 0; i < validUnsent.length; i++) System.out.println(" " + validUnsent[i]); } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { System.out.println(" ** ValidSent Addresses"); for (int i = 0; i < validSent.length; i++) System.out.println(" " + validSent[i]); } } System.out.println(); if (ex instanceof MessagingException) ex = ((MessagingException) ex).getNextException(); else ex = null; } while (ex != null); }
public void sendMessages() throws MessagingException { Transport transport = null; try { URLName url = new URLName("smtp", host, port, "", username, password); if (session == null) { createSession(); } transport = new com.sun.mail.smtp.SMTPTransport(session, url); transport.connect(host, port, username, password); for (MimeMessage message : messages) { // Attempt to send message, but catch exceptions caused by invalid // addresses so that other messages can continue to be sent. try { transport.sendMessage(message, message.getRecipients(MimeMessage.RecipientType.TO)); } catch (AddressException ae) { Log.error(ae.getMessage(), ae); } catch (SendFailedException sfe) { Log.error(sfe.getMessage(), sfe); } } } finally { if (transport != null) { try { transport.close(); } catch (MessagingException e) { /* ignore */ } } } }
@Test public void send_invoked_only_once_on_permanent_negative_response() { Mockito.doAnswer(invocation -> { throw new SendFailedException("550 rejected: mail rejected for policy reasons"); }).when(mailSender).send(any(MimeMessagePreparator.class)); try { subject.sendEmail("to", "subject", "test", ""); fail(); } catch (Exception e) { assertThat(e, instanceOf(SendFailedException.class)); verify(mailSender, times(1)).send(any(MimeMessagePreparator.class)); } }
/** * 开始发送邮件 * * @throws MessagingException * @throws SendFailedException */ public void sendMail() throws MessagingException, SendFailedException { if (mailToAddress == null) throw new MessagingException("请你必须你填写收件人地址!"); mailMessage.setContent(multipart); Transport.send(mailMessage); }
/** * Send email using GMail SMTP server. * * @param username GMail username * @param password GMail password * @param recipientEmail TO recipient * @param ccEmail CC recipient. Can be empty if there is no CC recipient * @param title title of the message * @param message message to be sent * @throws AddressException if the email address parse failed * @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage */ private static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException, EmailInesistente { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; // Get a Properties object Properties props = System.getProperties(); props.setProperty("mail.smtps.host", "smtp.gmail.com"); props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.socketFactory.port", "465"); props.setProperty("mail.smtps.auth", "true"); /* If set to false, the QUIT command is sent and the connection is immediately closed. If set to true (the default), causes the transport to wait for the response to the QUIT command. ref : http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html http://forum.java.sun.com/thread.jspa?threadID=5205249 smtpsend.java - demo program from javamail */ props.put("mail.smtps.quitwait", "false"); Session session = Session.getInstance(props, null); // -- Create a new message -- final MimeMessage msg = new MimeMessage(session); // -- Set the FROM and TO fields -- msg.setFrom(new InternetAddress(username + "@gmail.com")); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false)); if (ccEmail.length() > 0) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false)); } msg.setSubject(title); msg.setText(message, "utf-8"); msg.setSentDate(new Date()); SMTPTransport t = (SMTPTransport)session.getTransport("smtps"); t.connect("smtp.gmail.com", username, password); try{ t.sendMessage(msg, msg.getAllRecipients()); } catch (SendFailedException e){ throw new EmailInesistente(); } t.close(); }
/** * Realiza el envio de un email paginado * @param me * @param envio * @param destinatarios * @param fechaInicio * @return */ private static boolean enviarPaginaEmails(MensajeEmail me, Envio envio, List destinatarios, Date fechaInicio) { MobUtils utils = MobUtils.getInstance(); try { EmailUtils emailUtils = EmailUtils.getInstance(); Date now = new Date(); if((now.getTime()-fechaInicio.getTime()) > utils.getLimiteTiempo().longValue()){ log.debug("Cancelamos envio por haberse superado el tiempo Maximo del proceso de envio"); return false; } if (simularEnvioEmail.booleanValue()){ log.debug("Email simulando envio"); Date inicioSimulacion = new Date(); while ( (inicioSimulacion.getTime() + (simularEnvioDuracion * 1000)) > System.currentTimeMillis() ){ // Esperamos tiempo simulacion } log.debug("Email envio simulado"); }else{ emailUtils.enviar(prefijoEnvioEmail, me,envio,destinatarios); } return true; }catch (SendFailedException ex){ List invalidAddresses = null; List unsentAddresses = null; List validAddresses = null; if(ex.getInvalidAddresses() != null){ invalidAddresses = new ArrayList(); for(int i=0;i<ex.getInvalidAddresses().length;i++){ invalidAddresses.add(ex.getInvalidAddresses()[i].toString()); } } if(ex.getValidUnsentAddresses() != null){ unsentAddresses = new ArrayList(); for(int i=0;i<ex.getValidUnsentAddresses().length;i++){ unsentAddresses.add(ex.getValidUnsentAddresses()[i].toString()); } } if(ex.getValidSentAddresses() != null){ validAddresses = new ArrayList(); for(int i=0;i<ex.getValidSentAddresses().length;i++){ validAddresses.add(ex.getValidSentAddresses()[i].toString()); } } log.debug("Error generando correo para el envio: " + envio.getNombre(), ex); me.setError("Error generando correo para el envio: " + envio.getNombre() + "." + ex.getMessage()); me.setError(me.getError()+ " ERROR EMAILS: "); if(invalidAddresses != null){ me.setError(me.getError()+ "-no validos-" + invalidAddresses.toString()); } if(unsentAddresses != null){ me.setError(me.getError()+ "-no enviados-" + unsentAddresses.toString()); } me.setError(me.getError() + ": " + ex.getMessage()+ "."); me.setDestinatariosValidos(validAddresses); me.setEstado(ConstantesMobtratel.ESTADOENVIO_ERROR); } catch (DelegateException de) { log.debug("Error accediendo a la cuenta por defecto de EMAIL"); me.setError("Error accediendo a la cuenta por defecto de EMAIL"); me.setEstado(ConstantesMobtratel.ESTADOENVIO_ERROR); } catch (Exception e) { log.debug("Error generando correo para el envio: " + envio.getNombre()); me.setError("Error generando correo para el envio: " + envio.getNombre() + "." + e.getMessage()); me.setError(me.getError()+ "ERROR EMAILS: " + destinatarios.toString() + ": " + e.getMessage()+ "."); me.setEstado(ConstantesMobtratel.ESTADOENVIO_ERROR); } return false; }
private void handleException(MessagingException mex) { LOG.error("\n--Exception handling in MailHelper.java", mex); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { LOG.error(" ** Invalid Addresses", ex); if (invalid != null) { for (int i = 0; i < invalid.length; i++) { LOG.error(" " + invalid[i]); } } } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { LOG.error(" ** ValidUnsent Addresses", ex); if (validUnsent != null) { for (int i = 0; i < validUnsent.length; i++) { LOG.error(" " + validUnsent[i], ex); } } } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { LOG.error(" ** ValidSent Addresses", ex); if (validSent != null) { for (int i = 0; i < validSent.length; i++) { LOG.error(" " + validSent[i], ex); } } } } if (ex instanceof MessagingException) { ex = ((MessagingException) ex).getNextException(); } else { ex = null; } } while (ex != null); }
@Override protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException { return emailer.sendEmail(getTheToContactLists(), getSubject(), getBodyText(), getAttachements()); }
@Override protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException { String emailFromAsString = getFromIdentity().getAttributes().getEmail();//this mail is differently extracted in ContactForm return emailer.sendEmailCC(emailFromAsString, getSubject(), getBodyText(), getAttachements()); }
/** * Send a calendar message. * * @param strRecipientsTo * The list of the main recipients email. Every recipient must be separated by the mail separator defined in config.properties * @param strRecipientsCc * The recipients list of the carbon copies . * @param strRecipientsBcc * The recipients list of the blind carbon copies . * @param strSenderName * The sender name. * @param strSenderEmail * The sender email address. * @param strSubject * The message subject. * @param strMessage * The HTML message. * @param strCalendarMessage * The calendar message. * @param bCreateEvent * True to create the event, false to remove it * @param transport * the smtp transport object * @param session * the smtp session object * @throws AddressException * If invalid address * @throws SendFailedException * If an error occurred during sending * @throws MessagingException * If a messaging error occurred */ protected static void sendMessageCalendar( String strRecipientsTo, String strRecipientsCc, String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject, String strMessage, String strCalendarMessage, boolean bCreateEvent, Transport transport, Session session ) throws MessagingException, AddressException, SendFailedException { Message msg = prepareMessage( strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName, strSenderEmail, strSubject, session ); msg.setHeader( HEADER_NAME, HEADER_VALUE ); MimeMultipart multipart = new MimeMultipart( ); BodyPart msgBodyPart = new MimeBodyPart( ); msgBodyPart.setDataHandler( new DataHandler( new ByteArrayDataSource( strMessage, AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_HTML ) + AppPropertiesService.getProperty( PROPERTY_CHARSET ) ) ) ); multipart.addBodyPart( msgBodyPart ); BodyPart calendarBodyPart = new MimeBodyPart( ); // calendarBodyPart.addHeader( "Content-Class", "urn:content-classes:calendarmessage" ); calendarBodyPart.setContent( strCalendarMessage, AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_CALENDAR ) + AppPropertiesService.getProperty( PROPERTY_CHARSET ) + AppPropertiesService.getProperty( PROPERTY_CALENDAR_SEPARATOR ) + AppPropertiesService.getProperty( bCreateEvent ? PROPERTY_CALENDAR_METHOD_CREATE : PROPERTY_CALENDAR_METHOD_CANCEL ) ); calendarBodyPart.addHeader( HEADER_NAME, CONSTANT_BASE64 ); multipart.addBodyPart( calendarBodyPart ); msg.setContent( multipart ); sendMessage( msg, transport ); }
/** * Try to return a usefull logString created of the Exception which was * given. Return null if nothing usefull could be done * * @param e * The MessagingException to use * @return logString */ private String exceptionToLogString(Exception e) { if (e.getClass().getName().endsWith(".SMTPSendFailedException")) { return "RemoteHost said: " + e.getMessage(); } else if (e instanceof SendFailedException) { SendFailedException exception = (SendFailedException) e; // No error if (exception.getInvalidAddresses().length == 0 && exception.getValidUnsentAddresses().length == 0) return null; Exception ex; StringBuilder sb = new StringBuilder(); boolean smtpExFound = false; sb.append("RemoteHost said:"); if (e instanceof MessagingException) while ((ex = ((MessagingException) e).getNextException()) != null && ex instanceof MessagingException) { e = ex; if (ex.getClass().getName().endsWith(".SMTPAddressFailedException")) { try { InternetAddress ia = (InternetAddress) invokeGetter(ex, "getAddress"); sb.append(" ( " + ia + " - [" + ex.getMessage().replaceAll("\\n", "") + "] )"); smtpExFound = true; } catch (IllegalStateException ise) { // Error invoking the getAddress method } catch (ClassCastException cce) { // The getAddress method returned something // different than InternetAddress } } } if (!smtpExFound) { boolean invalidAddr = false; sb.append(" ( "); if (exception.getInvalidAddresses().length > 0) { sb.append(Arrays.toString(exception.getInvalidAddresses())); invalidAddr = true; } if (exception.getValidUnsentAddresses().length > 0) { if (invalidAddr == true) sb.append(" "); sb.append(Arrays.toString(exception.getValidUnsentAddresses())); } sb.append(" - ["); sb.append(exception.getMessage().replaceAll("\\n", "")); sb.append("] )"); } return sb.toString(); } return null; }
public void sendMessage(Message oMsg, Address[] aAddrs) throws NoSuchProviderException,SendFailedException,ParseException, MessagingException,NullPointerException { oMsg.setSentDate(new java.util.Date()); Transport.send(oMsg,aAddrs); }
/** * Send a text message. * * @param strRecipientsTo * The list of the main recipients email.Every recipient must be separated by the mail separator defined in config.properties * @param strRecipientsCc * The recipients list of the carbon copies . * @param strRecipientsBcc * The recipients list of the blind carbon copies . * @param strSenderName * The sender name. * @param strSenderEmail * The sender email address. * @param strSubject * The message subject. * @param strMessage * The message. * @param transport * the smtp transport object * @param session * the smtp session object * @throws AddressException * If invalid address * @throws SendFailedException * If an error occured during sending * @throws MessagingException * If a messaging error occured */ protected static void sendMessageText( String strRecipientsTo, String strRecipientsCc, String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject, String strMessage, Transport transport, Session session ) throws MessagingException, AddressException, SendFailedException { Message msg = prepareMessage( strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName, strSenderEmail, strSubject, session ); msg.setDataHandler( new DataHandler( new ByteArrayDataSource( strMessage, AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_PLAIN ) + AppPropertiesService.getProperty( PROPERTY_CHARSET ) ) ) ); sendMessage( msg, transport ); }
/** * Send a HTML formated message. * * @param strRecipientsTo * The list of the main recipients email.Every recipient must be separated by the mail separator defined in config.properties * @param strRecipientsCc * The recipients list of the carbon copies . * @param strRecipientsBcc * The recipients list of the blind carbon copies . * @param strSenderName * The sender name. * @param strSenderEmail * The sender email address. * @param strSubject * The message subject. * @param strMessage * The message. * @param transport * the smtp transport object * @param session * the smtp session object * @throws AddressException * If invalid address * @throws SendFailedException * If an error occured during sending * @throws MessagingException * If a messaging error occured */ protected static void sendMessageHtml( String strRecipientsTo, String strRecipientsCc, String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject, String strMessage, Transport transport, Session session ) throws MessagingException, AddressException, SendFailedException { Message msg = prepareMessage( strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName, strSenderEmail, strSubject, session ); msg.setHeader( HEADER_NAME, HEADER_VALUE ); // Message body formated in HTML msg.setDataHandler( new DataHandler( new ByteArrayDataSource( strMessage, AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_HTML ) + AppPropertiesService.getProperty( PROPERTY_CHARSET ) ) ) ); sendMessage( msg, transport ); }
public void sendMessage(Message oMsg) throws NoSuchProviderException,SendFailedException,ParseException, MessagingException,NullPointerException,IllegalStateException { oMsg.setSentDate(new java.util.Date()); Transport.send(oMsg); }
/** * @param mailto * @param subject * @param body * @return * @throws AddressException * @throws SendFailedException * @throws MessagingException TODO:gs handle exceptions internally and may return some error codes or so to get rid of dependecy of mail/activatoin jars in olat */ public boolean sendEmail(String mailto, String subject, String body) throws AddressException, SendFailedException, MessagingException { return sendEmail(mailfrom, mailto, subject, body); }
abstract protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException;