Java Code Examples for javax.mail.Message#setFrom()

The following examples show how to use javax.mail.Message#setFrom() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestMailClient.java    From holdmail with Apache License 2.0 7 votes vote down vote up
public void sendEmail(String fromEmail, String toEmail, String subject, String textBody, String htmlBody) {
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromEmail));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
        message.setSubject(subject);

        // Set the message
        createMultiMimePart(message, textBody, htmlBody);

        Transport.send(message);
    }
    catch (MessagingException e) {
        throw new HoldMailException("Failed to send email : " + e.getMessage(), e);
    }
}
 
Example 2
Source File: SendConfirmationEmailServlet.java    From ud859 with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String email = request.getParameter("email");
    String conferenceInfo = request.getParameter("conferenceInfo");
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    String body = "Hi, you have created a following conference.\n" + conferenceInfo;
    try {
        Message message = new MimeMessage(session);
        InternetAddress from = new InternetAddress(
                String.format("noreply@%s.appspotmail.com",
                        SystemProperty.applicationId.get()), "Conference Central");
        message.setFrom(from);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, ""));
        message.setSubject("You created a new Conference!");
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException e) {
        LOG.log(Level.WARNING, String.format("Failed to send an mail to %s", email), e);
        throw new RuntimeException(e);
    }
}
 
Example 3
Source File: SendConfirmationEmailServlet.java    From ud859 with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String email = request.getParameter("email");
    String conferenceInfo = request.getParameter("conferenceInfo");
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    String body = "Hi, you have created a following conference.\n" + conferenceInfo;
    try {
        Message message = new MimeMessage(session);
        InternetAddress from = new InternetAddress(
                String.format("noreply@%s.appspotmail.com",
                        SystemProperty.applicationId.get()), "Conference Central");
        message.setFrom(from);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, ""));
        message.setSubject("You created a new Conference!");
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException e) {
        LOG.log(Level.WARNING, String.format("Failed to send an mail to %s", email), e);
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: SMTPAppender.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 *   Address message.
 *   @param msg message, may not be null.
 *   @throws MessagingException thrown if error addressing message. 
 */
protected void addressMessage(final Message msg) throws MessagingException {
     if (from != null) {
		msg.setFrom(getAddress(from));
     } else {
		msg.setFrom();
  }

     if (to != null && to.length() > 0) {
           msg.setRecipients(Message.RecipientType.TO, parseAddress(to));
     }

    //Add CC receipients if defined.
 if (cc != null && cc.length() > 0) {
msg.setRecipients(Message.RecipientType.CC, parseAddress(cc));
 }

    //Add BCC receipients if defined.
 if (bcc != null && bcc.length() > 0) {
msg.setRecipients(Message.RecipientType.BCC, parseAddress(bcc));
 }
}
 
Example 5
Source File: ServerUtils.java    From sc2gears with Apache License 2.0 6 votes vote down vote up
/**
 * Sends an email.
 * @return true if no error occurred, false otherwise
 */
public static boolean sendEmail( final InternetAddress from, final InternetAddress to, final InternetAddress cc, final String subject, final String body ) {
	LOGGER.info( "Sending email to: " + to.toString() + ", subject: " + subject );
	final Session session = Session.getDefaultInstance( new Properties(), null );
	try {
		final Message message = new MimeMessage( session );
		message.setFrom( from );
		message.addRecipient( Message.RecipientType.TO, to );
		if ( cc != null )
			message.addRecipient( Message.RecipientType.CC, cc );
		message.addRecipient( Message.RecipientType.BCC, ADMIN_EMAIL );
		message.setSubject( "[Sc2gears Database] " + subject );
		message.setText( body );
		Transport.send( message );
		return true;
	} catch ( final Exception e ) {
		LOGGER.log( Level.SEVERE, "Failed to send email!", e );
		return false;
	}
}
 
Example 6
Source File: SMTPAppender.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Address message.
 *
 * @param msg message, may not be null.
 * @throws MessagingException thrown if error addressing message.
 */
private final void addressMessage(final Message msg) throws MessagingException {

   if (from != null) {
      msg.setFrom(getAddress(from));
   } else {
      msg.setFrom();
   }

   if (to != null && !to.isEmpty()) {
      msg.setRecipients(RecipientType.TO, parseAddress(to));
   }

   //Add CC recipients if defined.
   if (cc != null && !cc.isEmpty()) {
      msg.setRecipients(RecipientType.CC, parseAddress(cc));
   }

   //Add BCC recipients if defined.
   if (bcc != null && !bcc.isEmpty()) {
      msg.setRecipients(RecipientType.BCC, parseAddress(bcc));
   }
}
 
Example 7
Source File: SendMailConnector.java    From camunda-bpm-mail with Apache License 2.0 6 votes vote down vote up
protected Message createMessage(SendMailRequest request, Session session) throws Exception {

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(request.getFrom(), request.getFromAlias()));
    message.setRecipients(RecipientType.TO, InternetAddress.parse(request.getTo()));

    if (request.getCc() != null) {
      message.setRecipients(RecipientType.CC, InternetAddress.parse(request.getCc()));
    }
    if (request.getBcc() != null) {
      message.setRecipients(RecipientType.BCC, InternetAddress.parse(request.getBcc()));
    }

    message.setSentDate(new Date());
    message.setSubject(request.getSubject());

    if (hasContent(request)) {
      createMessageContent(message, request);
    } else {
      message.setText("");
    }

    return message;
  }
 
Example 8
Source File: MailSender.java    From SensorWebClient with GNU General Public License v2.0 5 votes vote down vote up
public static boolean sendDeleteProfileMail(String address, String userID) {
    LOGGER.debug("send delete profile mail to: " + address);

    String link = "?delete=" + userID;
    String text = SesConfig.mailDeleteProfile_en + ": " + "\n\n" +
    SesConfig.mailDeleteProfile_de + ": " + "\n\n" + SesConfig.URL + link;

    Session session = Session.getDefaultInstance(getProperties(), getMailAuthenticator());

    try {
        // send a new message
        Message msg = new MimeMessage(session);

        // set sender and receiver
        msg.setFrom(new InternetAddress(SesConfig.SENDER_ADDRESS));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address, false));

        // set subject
        msg.setSubject(SesConfig.mailSubjectDeleteProfile_en + "/" + SesConfig.mailSubjectDeleteProfile_de);
        msg.setText(text);
        msg.setSentDate(new Date());

        // send mail
        Transport.send(msg);
        LOGGER.debug("mail send succesfully done");
        return true;
    } catch (Exception e) {
        LOGGER.error("Error occured while sending delete profile mail: " + e.getMessage(), e);
    }
    return false;
}
 
Example 9
Source File: OutgoingMailSender.java    From holdmail with Apache License 2.0 5 votes vote down vote up
public void redirectMessage(String recipient, String rawBody) {

        // TODO: this is a crude first pass at bouncing a mail and probably needs to be a little more sophisticated

        try {

            Session session = getMailSession();
            Message message = initializeMimeMessage(rawBody, session);

            // wipe out ALL exisitng recipients
            message.setRecipients(Message.RecipientType.TO, new Address[]{});
            message.setRecipients(Message.RecipientType.CC, new Address[]{});
            message.setRecipients(Message.RecipientType.BCC, new Address[]{});

            // and set the new recipient
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));

            InternetAddress[] parsedFrom = InternetAddress.parse(getSenderFrom());
            if(parsedFrom.length > 0) {
                message.setFrom(parsedFrom[0]);
                logger.info("Outgoing mail will have From: " + parsedFrom[0].getAddress());
            }

            sendMessage(message);

            logger.info("Outgoing mail forwarded to " + recipient);

        } catch (MessagingException e) {
            throw new HoldMailException("couldn't send mail: " + e.getMessage(), e);
        }

    }
 
Example 10
Source File: AlertingService.java    From glowroot with Apache License 2.0 5 votes vote down vote up
public static void sendEmail(String centralDisplay, String agentRollupDisplay, String subject,
        List<String> emailAddresses, String messageText, SmtpConfig smtpConfig,
        @Nullable String passwordOverride, LazySecretKey lazySecretKey, MailService mailService)
        throws Exception {
    Session session = createMailSession(smtpConfig, passwordOverride, lazySecretKey);
    Message message = new MimeMessage(session);
    String fromEmailAddress = smtpConfig.fromEmailAddress();
    if (fromEmailAddress.isEmpty()) {
        String localServerName = InetAddress.getLocalHost().getHostName();
        fromEmailAddress = "glowroot@" + localServerName;
    }
    String fromDisplayName = smtpConfig.fromDisplayName();
    if (fromDisplayName.isEmpty()) {
        fromDisplayName = "Glowroot";
    }
    message.setFrom(new InternetAddress(fromEmailAddress, fromDisplayName));
    Address[] emailAddrs = new Address[emailAddresses.size()];
    for (int i = 0; i < emailAddresses.size(); i++) {
        emailAddrs[i] = new InternetAddress(emailAddresses.get(i));
    }
    message.setRecipients(Message.RecipientType.TO, emailAddrs);
    String subj = subject;
    if (!agentRollupDisplay.isEmpty()) {
        subj = "[" + agentRollupDisplay + "] " + subj;
    }
    if (!centralDisplay.isEmpty()) {
        subj = "[" + centralDisplay + "] " + subj;
    }
    if (agentRollupDisplay.isEmpty() && centralDisplay.isEmpty()) {
        subj = "[Glowroot] " + subj;
    }
    message.setSubject(subj);
    message.setText(messageText);
    mailService.send(message);
}
 
Example 11
Source File: MailUtil.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Common part for sending message process :
 * <ul>
 * <li>initializes a mail session with the SMTP server</li>
 * <li>activates debugging</li>
 * <li>instantiates and initializes a mime message</li>
 * <li>sets the sent date, the from field, the subject field</li>
 * <li>sets the recipients</li>
 * </ul>
 *
 *
 * @return the message object initialized with the common settings
 * @param mail
 *            The mail to send
 * @param session
 *            The SMTP session object
 * @throws AddressException
 *             If invalid address
 * @throws MessagingException
 *             If a messaging error occurred
 */
protected static Message prepareMessage( MailItem mail, Session session ) throws MessagingException
{
    // Instantiate and initialize a mime message
    Message msg = new MimeMessage( session );
    msg.setSentDate( new Date( ) );

    try
    {
        msg.setFrom( new InternetAddress( mail.getSenderEmail( ), mail.getSenderName( ), AppPropertiesService.getProperty( PROPERTY_CHARSET ) ) );
        msg.setSubject( MimeUtility.encodeText( mail.getSubject( ), AppPropertiesService.getProperty( PROPERTY_CHARSET ), ENCODING ) );
    }
    catch( UnsupportedEncodingException e )
    {
        throw new AppException( e.toString( ) );
    }

    // Instantiation of the list of address
    if ( mail.getRecipientsTo( ) != null )
    {
        msg.setRecipients( Message.RecipientType.TO, getAllAdressOfRecipients( mail.getRecipientsTo( ) ) );
    }

    if ( mail.getRecipientsCc( ) != null )
    {
        msg.setRecipients( Message.RecipientType.CC, getAllAdressOfRecipients( mail.getRecipientsCc( ) ) );
    }

    if ( mail.getRecipientsBcc( ) != null )
    {
        msg.setRecipients( Message.RecipientType.BCC, getAllAdressOfRecipients( mail.getRecipientsBcc( ) ) );
    }

    return msg;
}
 
Example 12
Source File: MailAlert.java    From dble-docs-cn with GNU General Public License v2.0 5 votes vote down vote up
private boolean sendMail(boolean isResolve, ClusterAlertBean clusterAlertBean) {
    try {
        Properties props = new Properties();

        // 开启debug调试
        props.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        // 设置邮件服务器主机名
        props.setProperty("mail.host", properties.getProperty(MAIL_SERVER));
        // 发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");

        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);

        Session session = Session.getInstance(props);

        Message msg = new MimeMessage(session);
        msg.setSubject("DBLE告警 " + (isResolve ? "RESOLVE\n" : "ALERT\n"));
        StringBuilder builder = new StringBuilder();
        builder.append(groupMailMsg(clusterAlertBean, isResolve));
        msg.setText(builder.toString());
        msg.setFrom(new InternetAddress(properties.getProperty(MAIL_SENDER)));

        Transport transport = session.getTransport();
        transport.connect(properties.getProperty(MAIL_SERVER), properties.getProperty(MAIL_SENDER), properties.getProperty(SENDER_PASSWORD));

        transport.sendMessage(msg, new Address[]{new InternetAddress(properties.getProperty(MAIL_RECEIVE))});
        transport.close();
        //send EMAIL SUCCESS return TRUE
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    //send fail reutrn false
    return false;
}
 
Example 13
Source File: SimpleMailSender.java    From KJFrameForAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * 以文本格式发送邮件
 * 
 * @param mailInfo
 *            待发送的邮件的信息
 */
public boolean sendTextMail(MailSenderInfo mailInfo) {
    // 判断是否需要身份认证
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
        // 如果需要身份认证,则创建一个密码验证器
        authenticator = new MyAuthenticator(mailInfo.getUserName(),
                mailInfo.getPassword());
    }
    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session sendMailSession = Session
            .getDefaultInstance(pro, authenticator);
    try {
        // 根据session创建一个邮件消息
        Message mailMessage = new MimeMessage(sendMailSession);
        // 创建邮件发送者地址
        Address from = new InternetAddress(mailInfo.getFromAddress());
        // 设置邮件消息的发送者
        mailMessage.setFrom(from);
        // 创建邮件的接收者地址,并设置到邮件消息中
        Address to = new InternetAddress(mailInfo.getToAddress());
        mailMessage.setRecipient(Message.RecipientType.TO, to);
        // 设置邮件消息的主题
        mailMessage.setSubject(mailInfo.getSubject());
        // 设置邮件消息发送的时间
        mailMessage.setSentDate(new Date());
        // 设置邮件消息的主要内容
        String mailContent = mailInfo.getContent();
        mailMessage.setText(mailContent);
        // 发送邮件
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
    return false;
}
 
Example 14
Source File: EmailTest.java    From light with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        final String username = "[email protected]";
        final String password = "sxwt2ysc";

        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "mail.networknt.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("[email protected]"));
            message.setSubject("Testing Subject");
            message.setContent("Hi,<br>Thanks for registering with us.<br>Please use the following <a href='http://www.networknt.com/api/rs?cmd={\"readOnly\":true,\"category\":\"user\",\"name\":\"activateUser\"}'>link</a> to activate your account.", "text/html; charset=utf-8");
            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
 
Example 15
Source File: AbstractMailSenderFactory.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 以文本格式发送邮件.
 *
 * @param mailSender 待发送的邮件的信息
 * @return Boolean
 */
protected boolean sendTextMail(final AbstractMailSender mailSender) {
    final Properties pro = mailSender.getProperties();
    MailAuthenticator authenticator = null;
    if (mailSender.isValidate()) {
        authenticator = new MailAuthenticator(mailSender.getUserName(), mailSender.getPassword());
    }
    
    final Session sendMailSession;
    if(singletonSessionInstance) {
        sendMailSession = Session.getDefaultInstance(pro, authenticator);
    } else {
        sendMailSession = Session.getInstance(pro, authenticator);
    }
    
    sendMailSession.setDebug(debugEnabled);
    try {
        final Message mailMessage = new MimeMessage(sendMailSession);
        final Address from = new InternetAddress(mailSender.getFromAddress());
        mailMessage.setFrom(from);
        mailMessage.setRecipients(Message.RecipientType.TO, toAddresses(mailSender.getToAddress()));
        mailMessage.setSubject(mailSender.getSubject());
        mailMessage.setSentDate(new Date());
        mailMessage.setText(mailSender.getContent());
        Transport.send(mailMessage);
        return true;
    } catch (final MessagingException ex) {
        LOGGER.error(ex.getMessage(), ex);
    }
    
    return false;
}
 
Example 16
Source File: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public static void sendMail( Context actualContext, Scriptable actualObject, Object[] ArgList,
  Function FunctionContext ) {

  boolean debug = false;

  // Arguments:
  // String smtp, String from, String recipients[ ], String subject, String message
  if ( ArgList.length == 5 ) {

    try {
      // Set the host smtp address
      Properties props = new Properties();
      props.put( "mail.smtp.host", ArgList[0] );

      // create some properties and get the default Session
      Session session = Session.getDefaultInstance( props, null );
      session.setDebug( debug );

      // create a message
      Message msg = new MimeMessage( session );

      // set the from and to address
      InternetAddress addressFrom = new InternetAddress( (String) ArgList[1] );
      msg.setFrom( addressFrom );

      // Get Recipients
      String[] strArrRecipients = ( (String) ArgList[2] ).split( "," );

      InternetAddress[] addressTo = new InternetAddress[strArrRecipients.length];
      for ( int i = 0; i < strArrRecipients.length; i++ ) {
        addressTo[i] = new InternetAddress( strArrRecipients[i] );
      }
      msg.setRecipients( Message.RecipientType.TO, addressTo );

      // Optional : You can also set your custom headers in the Email if you Want
      msg.addHeader( "MyHeaderName", "myHeaderValue" );

      // Setting the Subject and Content Type
      msg.setSubject( (String) ArgList[3] );
      msg.setContent( ArgList[4], "text/plain" );
      Transport.send( msg );
    } catch ( Exception e ) {
      throw Context.reportRuntimeError( "sendMail: " + e.toString() );
    }
  } else {
    throw Context.reportRuntimeError( "The function call sendMail requires 5 arguments." );
  }
}
 
Example 17
Source File: ScriptValuesAddedFunctions.java    From hop with Apache License 2.0 4 votes vote down vote up
public static void sendMail( Context actualContext, Scriptable actualObject, Object[] ArgList,
                             Function FunctionContext ) {

  boolean debug = false;

  // Arguments:
  // String smtp, String from, String recipients[ ], String subject, String message
  if ( ArgList.length == 5 ) {

    try {
      // Set the host smtp address
      Properties props = new Properties();
      props.put( "mail.smtp.host", ArgList[ 0 ] );

      // create some properties and get the default Session
      Session session = Session.getDefaultInstance( props, null );
      session.setDebug( debug );

      // create a message
      Message msg = new MimeMessage( session );

      // set the from and to address
      InternetAddress addressFrom = new InternetAddress( (String) ArgList[ 1 ] );
      msg.setFrom( addressFrom );

      // Get Recipients
      String[] strArrRecipients = ( (String) ArgList[ 2 ] ).split( "," );

      InternetAddress[] addressTo = new InternetAddress[ strArrRecipients.length ];
      for ( int i = 0; i < strArrRecipients.length; i++ ) {
        addressTo[ i ] = new InternetAddress( strArrRecipients[ i ] );
      }
      msg.setRecipients( Message.RecipientType.TO, addressTo );

      // Optional : You can also set your custom headers in the Email if you Want
      msg.addHeader( "MyHeaderName", "myHeaderValue" );

      // Setting the Subject and Content Type
      msg.setSubject( (String) ArgList[ 3 ] );
      msg.setContent( ArgList[ 4 ], "text/plain" );
      Transport.send( msg );
    } catch ( Exception e ) {
      throw Context.reportRuntimeError( "sendMail: " + e.toString() );
    }
  } else {
    throw Context.reportRuntimeError( "The function call sendMail requires 5 arguments." );
  }
}
 
Example 18
Source File: TestListenSMTP.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test(expected = MessagingException.class)
public void testListenSMTPwithTooLargeMessage() throws Exception {
    final ListenSMTP processor = new ListenSMTP();
    final TestRunner runner = TestRunners.newTestRunner(processor);

    final int port = NetworkUtils.availablePort();
    runner.setProperty(ListenSMTP.SMTP_PORT, String.valueOf(port));
    runner.setProperty(ListenSMTP.SMTP_MAXIMUM_CONNECTIONS, "3");
    runner.setProperty(ListenSMTP.SMTP_MAXIMUM_MSG_SIZE, "10 B");

    runner.run(1, false);

    assertTrue(String.format("expected server listening on %s:%d", "localhost", port), NetworkUtils.isListening("localhost", port, 5000));

    final Properties config = new Properties();
    config.put("mail.smtp.host", "localhost");
    config.put("mail.smtp.port", String.valueOf(port));
    config.put("mail.smtp.connectiontimeout", "5000");
    config.put("mail.smtp.timeout", "5000");
    config.put("mail.smtp.writetimeout", "5000");

    final Session session = Session.getInstance(config);
    session.setDebug(true);

    MessagingException messagingException = null;
    try {
        final Message email = new MimeMessage(session);
        email.setFrom(new InternetAddress("[email protected]"));
        email.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
        email.setSubject("This is a test");
        email.setText("MSG-0");
        Transport.send(email);
    } catch (final MessagingException e) {
        messagingException = e;
    }

    runner.shutdown();
    runner.assertAllFlowFilesTransferred(ListenSMTP.REL_SUCCESS, 0);

    if (messagingException != null) throw messagingException;
}
 
Example 19
Source File: EmailMessage.java    From BIMserver with GNU Affero General Public License v3.0 4 votes vote down vote up
public void send() throws MessagingException, UserException {
	Properties props = new Properties();
	ServerSettings serverSettings = bimServer.getServerSettingsCache().getServerSettings();
	props.put("mail.smtp.localhost", "bimserver.org");
	String smtpProps = serverSettings.getSmtpProtocol() == SmtpProtocol.SMTPS ? "mail.smtps.port" : "mail.smtp.port";
	
	props.put("mail.smtp.connectiontimeout", 10000);
	props.put("mail.smtp.timeout", 10000);
	props.put("mail.smtp.writetimeout", 10000);
	props.put("mail.smtp.host", serverSettings.getSmtpServer());
	props.put("mail.smtp.port", serverSettings.getSmtpPort());
	props.put("mail.smtp.auth", serverSettings.getSmtpUsername() != null);
	
	props.put(smtpProps, serverSettings.getSmtpPort());
	
	if (serverSettings.getSmtpProtocol() == SmtpProtocol.STARTTLS) {
		props.put("mail.smtp.starttls.enable","true");
	}

	Session session = null;
	
	if (serverSettings.getSmtpUsername() != null) {
		session = Session.getInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(serverSettings.getSmtpUsername(), serverSettings.getSmtpPassword());
			}
		});
	} else {
		session = Session.getInstance(props);
	}
	
	try {
		Message message = new MimeMessage(session);
		message.setSubject(subject);
		message.setRecipients(to, addressTo);
		message.setContent(body, contentType);
		message.setFrom(from);
		
		Transport.send(message, addressTo);
	} catch (MessagingException e) {
		LOGGER.error("Error sending email " + body + " " + e.getMessage());
		throw new UserException("Error sending email " + e.getMessage());
	}
}
 
Example 20
Source File: SimpleSmtpServerTest.java    From dumbster with Apache License 2.0 4 votes vote down vote up
@Test
public void testSendTwoMsgsWithLogin() throws Exception {
	String serverHost = "localhost";
	String from = "[email protected]";
	String to = "[email protected]";
	String subject = "Test";
	String body = "Test Body";

	Properties props = System.getProperties();

	if (serverHost != null) {
		props.setProperty("mail.smtp.host", serverHost);
	}

	Session session = Session.getDefaultInstance(props, null);
	Message msg = new MimeMessage(session);

	if (from != null) {
		msg.setFrom(new InternetAddress(from));
	} else {
		msg.setFrom();
	}

	InternetAddress.parse(to, false);
	msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
	msg.setSubject(subject);

	msg.setText(body);
	msg.setHeader("X-Mailer", "musala");
	msg.setSentDate(new Date());
	msg.saveChanges();

	Transport transport = null;

	try {
		transport = session.getTransport("smtp");
		transport.connect(serverHost, server.getPort(), "ddd", "ddd");
		transport.sendMessage(msg, InternetAddress.parse(to, false));
		transport.sendMessage(msg, InternetAddress.parse("[email protected]", false));
	} finally {
		if (transport != null) {
			transport.close();
		}
	}

	List<SmtpMessage> emails = this.server.getReceivedEmails();
	assertThat(emails, hasSize(2));
	SmtpMessage email = emails.get(0);
	assertTrue(email.getHeaderValue("Subject").equals("Test"));
	assertTrue(email.getBody().equals("Test Body"));
}