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

The following examples show how to use javax.mail.Message#setText() . 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: SmtpServerTest.java    From hawkular-alerts with Apache License 2.0 7 votes vote down vote up
@Test
public void checkSmtpServer() throws Exception {
    Properties props = new Properties();
    props.setProperty("mail.smtp.host", TEST_SMTP_HOST);
    props.setProperty("mail.smtp.port", String.valueOf(TEST_SMTP_PORT));

    Session session = Session.getInstance(props);

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("[email protected]"));
    message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse("[email protected]"));
    message.setSubject("Check SMTP Server");
    message.setText("This is the text of the message");
    Transport.send(message);

    assertEquals(1, server.getReceivedMessages().length);
}
 
Example 2
Source File: EmailSender.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
public void send(SendEmailRequest sendEmailRequest) {
    try {
        Session session = session();
        Message message = new MimeMessage(session);
        message.setSubject(sendEmailRequest.subject);
        if (sendEmailRequest.mimeType == MimeType.HTML) {
            message.setContent(sendEmailRequest.content, "text/html;charset=UTF-8");
        } else {
            message.setText(sendEmailRequest.content);
        }

        message.setFrom(new EmailName(session.getProperty("mail.user")).toAddress());
        message.setReplyTo(new Address[]{new EmailName(this.session.getProperty("mail.replyTo")).toAddress()});
        Transport transport = session.getTransport();
        transport.connect();
        transport.sendMessage(message, addresses(sendEmailRequest.to));
        transport.close();
    } catch (MessagingException | UnsupportedEncodingException e) {
        logger.error("failed to send email, to={}, subject={}", sendEmailRequest.to, sendEmailRequest.subject, 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: 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 5
Source File: CustomerMasterService.java    From jVoiD with Apache License 2.0 5 votes vote down vote up
public void sendEmail(String email, String password){
	
	Properties properties = System.getProperties();
	properties.put("mail.smtp.starttls.enable", "true");
	properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.auth", false);
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.port", 587);
    Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication("[email protected]", "test123");
		}
    });
    
    try {
    	 
		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress("[email protected]"));
		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
		message.setSubject("Reset Password");
		String content = "Your new password is " + password;
		message.setText(content);
			Transport.send(message);

	} catch (MessagingException e) {
		throw new RuntimeException(e);
	}
}
 
Example 6
Source File: DefaultMailService.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void sendMessage ( final String to, final String subject, final String text, final String html ) throws Exception
{
    // create message

    final Message message = createMessage ( to, subject );

    if ( html != null && !html.isEmpty () )
    {
        // create multipart

        final Multipart parts = new MimeMultipart ( "alternative" );

        // set text

        final MimeBodyPart textPart = new MimeBodyPart ();
        textPart.setText ( text, "UTF-8" );
        parts.addBodyPart ( textPart );

        // set HTML, optionally

        final MimeBodyPart htmlPart = new MimeBodyPart ();
        htmlPart.setContent ( html, "text/html; charset=utf-8" );
        parts.addBodyPart ( htmlPart );

        // set parts

        message.setContent ( parts );
    }
    else
    {
        // plain text
        message.setText ( text );
    }

    // send message

    sendMessage ( message );
}
 
Example 7
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 8
Source File: MailTask.java    From oodt with Apache License 2.0 5 votes vote down vote up
public void run(Metadata metadata, WorkflowTaskConfiguration config)
    throws WorkflowTaskInstanceException {
  Properties mailProps = new Properties();
  mailProps.setProperty("mail.host", "smtp.jpl.nasa.gov");
  mailProps.setProperty("mail.user", "mattmann");
  
  Session session = Session.getInstance(mailProps);

  String msgTxt = "Hello "
      + config.getProperty("user.name")
      + ":\n\n"
      + "You have successfully ingested the file with the following metadata: \n\n"
      + getMsgStringFromMet(metadata) + "\n\n" + "Thanks!\n\n" + "CAS";

  Message msg = new MimeMessage(session);
  try {
    msg.setSubject(config.getProperty("msg.subject"));
    msg.setSentDate(new Date());
    msg.setFrom(InternetAddress.parse(config.getProperty("mail.from"))[0]);
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(config
        .getProperty("mail.to"), false));
    msg.setText(msgTxt);
    Transport.send(msg);

  } catch (MessagingException e) {
    throw new WorkflowTaskInstanceException(e.getMessage());
  }

}
 
Example 9
Source File: MailSender.java    From SensorWebClient with GNU General Public License v2.0 5 votes vote down vote up
public static void sendRegisterMail(String address, String id, String userName) {
    LOGGER.debug("send register mail to: " + address);

    String link = "?user=" + id;
    String tempText_de = SesConfig.mailTextRegister_de.replace("_NAME_", userName);
    String tempText_en = SesConfig.mailTextRegister_en.replace("_NAME_", userName);
    
    String text = tempText_en + "\n" + tempText_de + "\n" + SesConfig.URL + link;

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

    try {
        // create 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 to mail
        msg.setSubject(SesConfig.mailSubjectRegister_en + "/" + SesConfig.mailSubjectRegister_de);
        msg.setText(text);
        msg.setSentDate(new Date());

        // send message
        Transport.send(msg);
        LOGGER.debug("mail send succesfully done");
    } catch (Exception e) {
        LOGGER.error("Error occured while sending register mail: " + e.getMessage(), e);
    }
}
 
Example 10
Source File: MailSender.java    From SMS302 with Apache License 2.0 5 votes vote down vote up
boolean send(String title, String body, String toAddr) {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", HOST);
    props.put("mail.smtp.port", PORT);

    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(USER_NAME, PASSWORD);
                }
            });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(USER_NAME));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(toAddr));
        message.setSubject(title);
        message.setText(body);

        Transport.send(message);

        System.out.println("Mail sent.");
        return true;

    } catch (MessagingException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 11
Source File: EmailActionExecutor.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
/** @param item Item for which to send email
 *  @param addresses Recipients
 */
static void sendEmail(final AlarmTreeItem<?> item, final String[] addresses)
{
    logger.log(Level.INFO, item.getPathName() + ": Send email to " + Arrays.toString(addresses));

    final String title = createTitle(item);
    final String body = createBody(item);

    final Properties props = new Properties();
    props.put("mail.smtp.host", EmailPreferences.mailhost);
    props.put("mail.smtp.port", EmailPreferences.mailport);

    final Session session = Session.getDefaultInstance(props);

    for (String address : addresses)
        try
        {
            final Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(AlarmSystem.automated_email_sender));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address));
            message.setSubject(title);
            message.setText(body);

            Transport.send(message);
        }
        catch (Exception ex)
        {
            logger.log(Level.WARNING, "Failed to email to " + address, ex);
        }
}
 
Example 12
Source File: EmailSender.java    From core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sends e-mail to the specified recipients.
 * 
 * @param recipients
 *            Comma separated list of recipient e-mail addresses
 * @param subject
 *            Subject for the e-mail
 * @param messageBody
 *            The body for the e-mail
 */
public void send(String recipients, String subject, String messageBody) {
	Message message = new MimeMessage(session);
	
	try {

		message.setRecipients(Message.RecipientType.TO,
				InternetAddress.parse(recipients));
		message.setSubject(subject);
		message.setText(messageBody);

		Transport.send(message);

		logger.info("Successfully sent e-mail to {} . The e-mail "
				+ "message subject was: \"{}\", and body was: \"{}\"", 
				recipients, subject, messageBody);
	} catch (MessagingException e) {
		// Since this is a serious issue log the error and send an e-mail 
		// via logback
		logger.error(Markers.email(), 
				"Failed sending e-mail for agencyId={}. The e-mail config "
				+ "file {} specified by the Java property {} contains the "
				+ "login info to the SMTP server. Exception message: {}. "
				+ "The e-mail message subject was: \"{}\", and body "
				+ "was: \"{}\"",
				AgencyConfig.getAgencyId(), emailConfigFile.getID(), 
				emailConfigFile.getValue(),	e.getMessage(), subject, 
				messageBody);
	}
}
 
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: MailSender.java    From SensorWebClient with GNU General Public License v2.0 5 votes vote down vote up
public static boolean sendSensorDeactivatedMail(String address, String sensorID) {
    LOGGER.debug("send email validation mail to: " + address);

    String text = SesConfig.mailSubjectSensor_en + ": " + "\n" +
    SesConfig.mailSubjectSensor_de + ": " + "\n\n" +
    sensorID;

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

    try {
        // create a 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.mailSubjectSensor_en + "/" + SesConfig.mailSubjectSensor_de);
        msg.setText(text);
        msg.setSentDate(new Date());

        // send mail
        Transport.send(msg);
        LOGGER.debug("mail send succesfully done");
        return true;
    } catch (MessagingException e) {
        LOGGER.error("Error occured while sending sensor deactivation mail: " + e.getMessage(), e);
    }
    return false;
}
 
Example 15
Source File: TestListenSMTP.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testListenSMTPwithTLS() 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");

    // Setup the SSL Context
    final SSLContextService sslContextService = new StandardRestrictedSSLContextService();
    runner.addControllerService("ssl-context", sslContextService);
    runner.setProperty(sslContextService, StandardSSLContextService.TRUSTSTORE, "src/test/resources/truststore.jks");
    runner.setProperty(sslContextService, StandardSSLContextService.TRUSTSTORE_PASSWORD, "passwordpassword");
    runner.setProperty(sslContextService, StandardSSLContextService.TRUSTSTORE_TYPE, "JKS");
    runner.setProperty(sslContextService, StandardSSLContextService.KEYSTORE, "src/test/resources/keystore.jks");
    runner.setProperty(sslContextService, StandardSSLContextService.KEYSTORE_PASSWORD, "passwordpassword");
    runner.setProperty(sslContextService, StandardSSLContextService.KEYSTORE_TYPE, "JKS");
    runner.enableControllerService(sslContextService);

    // and add the SSL context to the runner
    runner.setProperty(ListenSMTP.SSL_CONTEXT_SERVICE, "ssl-context");
    runner.setProperty(ListenSMTP.CLIENT_AUTH, SslContextFactory.ClientAuth.NONE.name());
    runner.assertValid();

    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.auth", "false");
    config.put("mail.smtp.starttls.enable", "true");
    config.put("mail.smtp.starttls.required", "true");
    config.put("mail.smtp.ssl.trust", "*");
    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);

    final int numMessages = 5;
    for (int i = 0; i < numMessages; i++) {
        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-" + i);
        Transport.send(email);
    }

    runner.shutdown();
    runner.assertAllFlowFilesTransferred(ListenSMTP.REL_SUCCESS, numMessages);
}
 
Example 16
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"));
}
 
Example 17
Source File: SimpleMailSender.java    From disconf with Apache License 2.0 4 votes vote down vote up
/**
 * 以文本格式发送邮件
 *
 * @param mailInfo 待发送的邮件的信息
 */
public static boolean sendTextMail(MailSenderInfo mailInfo) {

    try {

        // 设置一些通用的数据
        Message mailMessage = setCommon(mailInfo);

        // 设置邮件消息的主要内容
        String mailContent = mailInfo.getContent();
        mailMessage.setText(mailContent);

        // 发送邮件
        Transport.send(mailMessage);

        return true;

    } catch (MessagingException ex) {

        ex.printStackTrace();
    }

    return false;
}
 
Example 18
Source File: EmailUtil.java    From Library-Assistant with Apache License 2.0 4 votes vote down vote up
public static void sendTestMail(MailServerInfo mailServerInfo, String recepient, GenericCallback callback) {

        Runnable emailSendTask = () -> {
            LOGGER.log(Level.INFO, "Initiating email sending task. Sending to {}", recepient);
            Properties props = new Properties();
            try {
                MailSSLSocketFactory sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
                props.put("mail.imap.ssl.trust", "*");
                props.put("mail.imap.ssl.socketFactory", sf);
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.starttls.enable", mailServerInfo.getSslEnabled() ? "true" : "false");
                props.put("mail.smtp.host", mailServerInfo.getMailServer());
                props.put("mail.smtp.port", mailServerInfo.getPort());

                Session session = Session.getInstance(props, new javax.mail.Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(mailServerInfo.getEmailID(), mailServerInfo.getPassword());
                    }
                });

                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(mailServerInfo.getEmailID()));
                message.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse(recepient));
                message.setSubject("Test mail from Library Assistant");
                message.setText("Hi,"
                        + "\n\n This is a test mail from Library Assistant!");

                Transport.send(message);
                LOGGER.log(Level.INFO, "Everything seems fine");
                callback.taskCompleted(Boolean.TRUE);
            } catch (Throwable exp) {
                LOGGER.log(Level.INFO, "Error occurred during sending email", exp);
                callback.taskCompleted(Boolean.FALSE);
            }
        };
        Thread mailSender = new Thread(emailSendTask, "EMAIL-SENDER");
        mailSender.start();
    }
 
Example 19
Source File: RecoverController.java    From airsonic-advanced with GNU General Public License v3.0 4 votes vote down vote up
private boolean emailPassword(String password, String username, String email) {
    /* Default to protocol smtp when SmtpEncryption is set to "None" */
    String prot = "smtp";

    if (settingsService.getSmtpServer() == null || settingsService.getSmtpServer().isEmpty()) {
        LOG.warn("Can not send email; no Smtp server configured.");
        return false;
    }

    Properties props = new Properties();
    if (settingsService.getSmtpEncryption().equals("SSL/TLS")) {
        prot = "smtps";
        props.put("mail." + prot + ".ssl.enable", "true");
    } else if (settingsService.getSmtpEncryption().equals("STARTTLS")) {
        prot = "smtp";
        props.put("mail." + prot + ".starttls.enable", "true");
    }
    props.put("mail." + prot + ".host", settingsService.getSmtpServer());
    props.put("mail." + prot + ".port", settingsService.getSmtpPort());
    /* use authentication when SmtpUser is configured */
    if (settingsService.getSmtpUser() != null && !settingsService.getSmtpUser().isEmpty()) {
        props.put("mail." + prot + ".auth", "true");
    }

    Session session = Session.getInstance(props, null);

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(settingsService.getSmtpFrom()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject("Airsonic Password");
        message.setText("Hi there!\n\n" +
                "You have requested to reset your Airsonic password.  Please find your new login details below.\n\n" +
                "Username: " + username + "\n" +
                "Password: " + password + "\n\n" +
                "--\n" +
                "Your Airsonic server\n" +
                "airsonic.github.io/");
        message.setSentDate(Date.from(Instant.now()));

        Transport trans = session.getTransport(prot);
        try {
            if (props.get("mail." + prot + ".auth") != null && props.get("mail." + prot + ".auth").equals("true")) {
                trans.connect(settingsService.getSmtpServer(), settingsService.getSmtpUser(), settingsService.getSmtpPassword());
            } else {
                trans.connect();
            }
            trans.sendMessage(message, message.getAllRecipients());
        } finally {
            trans.close();
        }
        return true;

    } catch (Exception x) {
        LOG.warn("Failed to send email.", x);
        return false;
    }
}
 
Example 20
Source File: DefaultMailService.java    From packagedrone with Eclipse Public License 1.0 3 votes vote down vote up
@Override
public void sendMessage ( final String to, final String subject, final Readable readable ) throws Exception
{
    // create message

    final Message message = createMessage ( to, subject );

    // set text

    message.setText ( CharStreams.toString ( readable ) );

    // send message

    sendMessage ( message );
}