Java Code Examples for javax.mail.internet.MimeMessage#addRecipient()

The following examples show how to use javax.mail.internet.MimeMessage#addRecipient() . 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: EmailService.java    From fido2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void sendEmail(String email, String subjectline, String content) throws UnsupportedEncodingException{
    try{
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(
                Configurations.getConfigurationProperty("poc.cfg.property.smtp.from"),
                Configurations.getConfigurationProperty("poc.cfg.property.smtp.fromName")));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
        message.setSubject(subjectline);

        if(Configurations.getConfigurationProperty("poc.cfg.property.email.type").equalsIgnoreCase("HTML")){
            message.setContent(content, "text/html; charset=utf-8");
        }
        else{
            message.setText(content);
        }

        Transport.send(message);
    } catch (MessagingException ex) {
        ex.printStackTrace();
        POCLogger.logp(Level.SEVERE, CLASSNAME, "callSKFSRestApi", "POC-ERR-5001", ex.getLocalizedMessage());
    }
}
 
Example 2
Source File: EmailSender.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * Send email with a string content.
 *
 * @param to destination email address
 * @param subject email subject
 * @param content email content
 * @throws MessagingException message exception
 */
public void sendMail (String to, String subject, String content) throws MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.user", emailConfg.getUser());
    props.put("mail.smtp.host", emailConfg.getHost());
    props.put("mail.smtp.port", emailConfg.getPort());
    props.put("mail.smtp.starttls.enable","true");
    props.put("mail.smtp.debug", emailConfg.getDebug());
    props.put("mail.smtp.auth", emailConfg.getAuth());
    props.put("mail.smtp.ssl.trust", emailConfg.host);

    String pass = emailConfg.getPass();
    if(pass == null) {
        Map<String, Object> secret = Config.getInstance().getJsonMapConfig(CONFIG_SECRET);
        pass = (String)secret.get(SecretConstants.EMAIL_PASSWORD);
    }

    SMTPAuthenticator auth = new SMTPAuthenticator(emailConfg.getUser(), pass);
    Session session = Session.getInstance(props, auth);

    MimeMessage message = new MimeMessage(session);

    message.setFrom(new InternetAddress(emailConfg.getUser()));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

    message.setSubject(subject);

    message.setContent(content, "text/html");

    // Send message
    Transport.send(message);
    if(logger.isInfoEnabled()) logger.info("An email has been sent to " + to + " with subject " + subject);
}
 
Example 3
Source File: Email.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Send the email reply.
 * @throws MessagingException 
 */
public void sendEmail(String text, String subject, String replyTo, boolean throwException) throws MessagingException {
	log("Sending email:", Level.INFO, replyTo, subject, text);
	initProperties();
	try {
		//Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
		//props.setProperty("mail.transport.protocol", "smtp");
		//props.setProperty("mail.host", getOutgoingHost());

		Session session = connectSession();
		
		/*props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", String.valueOf(getOutgoingPort()));
		props.put("mail.smtp.socketFactory.port", String.valueOf(getOutgoingPort()));
		props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.socketFactory.fallback", "false");
		props.setProperty("mail.smtp.quitwait", "false");*/
		
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(getEmailAddress()));
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(replyTo));
		message.setSubject(subject);
		if (Utils.containsHTML(text)) {
			message.setContent(text, "text/html; charset=UTF-8");
		} else {
			message.setText(text);
		}

		// Send message
		this.emails++;
		Transport.send(message);
	} catch (MessagingException exception) {
		log(new BotException("Failed to send email: " + exception.getMessage(), exception));
		if (throwException) { throw exception; }
	}
}
 
Example 4
Source File: MailLogger.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 *  Send the mail
 *
 * @param  aMailhost mail server
 * @param  aFrom from address
 * @param  aToList comma-separated recipient list
 * @param  aSubject mail subject
 * @param  aText mail body
 * @throws Exception if sending message fails
 */
private void sendMail(String aMailhost, String aFrom, String aToList,
        String aSubject, String aText)
    throws Exception
{
    // Get system properties
    final Properties props = System.getProperties();

    // Setup mail server
    props.put("mail.smtp.host", aMailhost);

    // Get session
    final Session session = Session.getDefaultInstance(props, null);

    // Define message
    final MimeMessage message = new MimeMessage(session);

    message.setFrom(new InternetAddress(aFrom));
    final StringTokenizer t = new StringTokenizer(aToList, ", ", false);
    while (t.hasMoreTokens()) {
        message.addRecipient(
            MimeMessage.RecipientType.TO,
            new InternetAddress(t.nextToken()));
    }
    message.setSubject(aSubject);
    message.setText(aText);

    Transport.send(message);
}
 
Example 5
Source File: MailLogger.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 *  Send the mail
 *
 * @param  aMailhost mail server
 * @param  aFrom from address
 * @param  aToList comma-separated recipient list
 * @param  aSubject mail subject
 * @param  aText mail body
 * @throws Exception if sending message fails
 */
private void sendMail(String aMailhost, String aFrom, String aToList,
        String aSubject, String aText)
    throws Exception
{
    // Get system properties
    final Properties props = System.getProperties();

    // Setup mail server
    props.put("mail.smtp.host", aMailhost);

    // Get session
    final Session session = Session.getDefaultInstance(props, null);

    // Define message
    final MimeMessage message = new MimeMessage(session);

    message.setFrom(new InternetAddress(aFrom));
    final StringTokenizer t = new StringTokenizer(aToList, ", ", false);
    while (t.hasMoreTokens()) {
        message.addRecipient(
            MimeMessage.RecipientType.TO,
            new InternetAddress(t.nextToken()));
    }
    message.setSubject(aSubject);
    message.setText(aText);

    Transport.send(message);
}
 
Example 6
Source File: MailTestUtil.java    From camunda-bpm-mail with Apache License 2.0 5 votes vote down vote up
public static MimeMessage createMimeMessage(Session session) throws MessagingException, AddressException {
  MimeMessage message = new MimeMessage(session);

  message.setFrom(new InternetAddress("[email protected]"));
  message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
  message.setSubject("subject");

  return message;
}
 
Example 7
Source File: ITestConsumeEmail.java    From nifi with Apache License 2.0 5 votes vote down vote up
public void addMessage(String testName, GreenMailUser user) throws MessagingException {
    Properties prop = new Properties();
    Session session = Session.getDefaultInstance(prop);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress("[email protected]"));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
    message.setSubject("Test email" + testName);
    message.setText("test test test chocolate");
    user.deliver(message);
}
 
Example 8
Source File: MailUtil.java    From sdudoc with MIT License 5 votes vote down vote up
/** 发送密码重置的邮件 */
public static void sendResetPasswordEmail(User user) {
	String subject = "sdudoc密码重置提醒";
	String content = "您于" + DocUtil.getDateTime() + "在sdudoc找回密码,点击以下链接,进行密码重置:"
			+ "http://127.0.0.1:8080/sdudoc/resetPasswordCheck.action?user.username=" + user.getUsername()
			+ "&user.checkCode=" + user.getCheckCode() + " 为保障您的帐号安全,请在24小时内点击该链接,您也可以将链接复制到浏览器地址栏访问。"
			+ "若您没有申请密码重置,请您忽略此邮件,由此给您带来的不便请谅解。";

	// session.setDebug(true);

	String from = "[email protected]"; // 发邮件的出发地(发件人的信箱)
	Session session = getMailSession();
	// 定义message
	MimeMessage message = new MimeMessage(session);
	try {
		message.setFrom(new InternetAddress(from));
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
		message.setSubject(subject);
		BodyPart mdp = new MimeBodyPart();
		mdp.setContent(content, "text/html;charset=utf8");
		Multipart mm = new MimeMultipart();
		mm.addBodyPart(mdp);
		message.setContent(mm);
		message.saveChanges();
		Transport.send(message);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 9
Source File: SMTPMailManagerImpl.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
public void send(String to, String title, String message) throws Exception {
    Session session = Session.getDefaultInstance(properties, getAuthenticator());
    // Create a default MimeMessage object.
    MimeMessage mimeMessage = new MimeMessage(session);
    // Set From: header field of the header.
    mimeMessage.setFrom(new InternetAddress(adminAddress));
    // Set To: header field of the header.
    mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    // Set Subject: header field
    mimeMessage.setSubject(title);
    // Now set the actual message
    mimeMessage.setText(message);
    // Send message
    Transport.send(mimeMessage);
}
 
Example 10
Source File: MessageContentTest.java    From subethasmtp with Apache License 2.0 5 votes vote down vote up
/** */
public void testMultipleRecipients() throws Exception
{
	MimeMessage message = new MimeMessage(this.session);
	message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	message.setFrom(new InternetAddress("[email protected]"));
	message.setSubject("barf");
	message.setText("body");

	Transport.send(message);

	assertEquals(2, this.wiser.getMessages().size());
}
 
Example 11
Source File: TestConsumeEmail.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public void addMessage(String testName, GreenMailUser user) throws MessagingException {
    Properties prop = new Properties();
    Session session = Session.getDefaultInstance(prop);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress("[email protected]"));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
    message.setSubject("Test email" + testName);
    message.setText("test test test chocolate");
    user.deliver(message);
}
 
Example 12
Source File: Email.java    From OpenSZZ-Cloud-Native with GNU General Public License v3.0 5 votes vote down vote up
public boolean sentEmail(){
      try {
    	       htmlText = "<p>The project " +projectName+ " "
    	       		+ "you submitted has been analysed.</p> <div>"
    	       		+ "<p>Here you can download the csv file containing the BugInducingCommits of the project."
    	       		+ "</p></div><div><p>You can download the csv using the token "+token+" or with this link "
    	       		+ "<a href=\""+urlWebService+"\">Link</a></p></div>";
    	 
          // Create a default MimeMessage object.
          MimeMessage message = new MimeMessage(session);

          // Set From: header field of the header.
          message.setFrom(new InternetAddress(username));

          // Set To: header field of the header.
          message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo));

          // Set Subject: header field
          message.setSubject("Analysis project " + projectName);
          message.setContent(htmlText, "text/html; charset=utf-8");
          

          // Send message
          Transport.send(message);
          System.out.println("Sent message successfully....");
       } catch (MessagingException mex) {
          mex.printStackTrace();
          return false;
       }
	return true;
}
 
Example 13
Source File: Email.java    From OpenSZZ-Cloud-Native with GNU General Public License v3.0 5 votes vote down vote up
public boolean sentEmail(){
      try {
    	       htmlText = "<p>The project " +projectName+ " "
    	       		+ "you submitted has been analysed.</p> <div>"
    	       		+ "<p>Here you can download the csv file containing the BugInducingCommits of the project."
    	       		+ "</p></div><div><p>You can download the csv using the token "+token+" or with this link "
    	       		+ "<a href=\""+urlWebService+"\">Link</a></p></div>";
    	 
          // Create a default MimeMessage object.
          MimeMessage message = new MimeMessage(session);

          // Set From: header field of the header.
          message.setFrom(new InternetAddress(username));

          // Set To: header field of the header.
          message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo));

          // Set Subject: header field
          message.setSubject("Analysis project " + projectName);
          message.setContent(htmlText, "text/html; charset=utf-8");
          

          // Send message
          Transport.send(message);
          System.out.println("Sent message successfully....");
       } catch (MessagingException mex) {
          mex.printStackTrace();
          return false;
       }
	return true;
}
 
Example 14
Source File: EmailSender.java    From kmanager with Apache License 2.0 4 votes vote down vote up
public static void sendEmail(String message, String sendTo, String group_topic) {
  Properties properties = System.getProperties();

  if (config.getSmtpAuth()) {
    properties.setProperty("mail.user", config.getSmtpUser());
    properties.setProperty("mail.password", config.getSmtpPasswd());
  }
  properties.setProperty("mail.smtp.host", config.getSmtpServer());

  Session session = Session.getDefaultInstance(properties);

  MimeMessage mimeMessage = new MimeMessage(session);

  try {
    String[] sendToArr = sendTo.split(";");
    mimeMessage.setFrom(new InternetAddress(config.getMailSender()));
    if (sendToArr.length > 1) {
      String cc = "";
      for (int i = 1; i < sendToArr.length; i++) {
        cc += i == sendToArr.length - 1 ? sendToArr[i] : sendToArr[i] + ",";
      }
      mimeMessage.addRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
    }
    mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(sendToArr[0]));

    String[] group_topicArr = group_topic.split("_");
    String subject = config.getMailSubject();
    if (subject.contains("{group}")) {
      subject = subject.replace("{group}", group_topicArr[0]);
    }
    if (subject.contains("{topic}")) {
      subject = subject.replace("{topic}", group_topicArr[1]);
    }
    mimeMessage.setSubject(subject);
    mimeMessage.setSentDate(new Date());
    mimeMessage.setContent(message, "text/html");

    Transport.send(mimeMessage);
  } catch (

  Exception e) {
    LOG.error("sendEmail faild!", e);
  }
}
 
Example 15
Source File: DefaultSendEmailProvider.java    From xframium-java with GNU General Public License v3.0 4 votes vote down vote up
public boolean _sendEmail(String fromAddress, String[] toAddress, String subjectLine, String emailBody, final Map<String,String> propertyMap ) 
{
    Properties mailProps = new Properties();
    
    mailProps.putAll( propertyMap );
    
    try
    {
        Session serverSession = null;
        
        if ( propertyMap.containsKey( USER_NAME ) )
        {
            serverSession = Session.getInstance( mailProps,
                    new javax.mail.Authenticator() {
                      protected PasswordAuthentication getPasswordAuthentication() {
                          return new PasswordAuthentication(propertyMap.get( USER_NAME ), propertyMap.get( PASSWORD ) );
                      }
                    });
        }
        else
            serverSession = Session.getDefaultInstance(mailProps);
        
        MimeMessage newMessage = new MimeMessage( serverSession );
        
        newMessage.setFrom( new InternetAddress( fromAddress ) );
        
        for ( String to : toAddress )
            newMessage.addRecipient(Message.RecipientType.TO, new InternetAddress( to ) );
        
        newMessage.setSubject(subjectLine);
        newMessage.setText(emailBody);
        Transport.send(newMessage);
        return true;
        
    }
    catch( Exception e )
    {
        log.error( "Error sending email message", e );
        return false;
    }
}
 
Example 16
Source File: DKIMSignTest.java    From james-project with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@ValueSource(strings = {PKCS1_PEM_FILE, PKCS8_PEM_FILE})
void testDKIMSignMessageAsText(String pemFile) throws MessagingException,
        IOException, FailException {
    MimeMessage mm = new MimeMessage(Session
            .getDefaultInstance(new Properties()));
    mm.addFrom(new Address[]{new InternetAddress("[email protected]")});
    mm.addRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mm.setText("An 8bit encoded body with €uro symbol.", "ISO-8859-15");

    Mailet mailet = new DKIMSign();

    FakeMailetConfig mci = FakeMailetConfig.builder()
            .mailetName("Test")
            .mailetContext(FAKE_MAIL_CONTEXT)
            .setProperty(
                    "signatureTemplate",
                    "v=1; s=selector; d=example.com; h=from:to:received:received; a=rsa-sha256; bh=; b=;")
            .setProperty("privateKeyFilepath", pemFile)
            .build();

    mailet.init(mci);

    Mail mail = FakeMail.builder()
        .name("test")
        .mimeMessage(mm)
        .build();

    Mailet m7bit = new ConvertTo7Bit();
    m7bit.init(mci);

    mailet.service(mail);

    m7bit.service(mail);

    ByteArrayOutputStream rawMessage = new ByteArrayOutputStream();
    mail.getMessage().writeTo(rawMessage);

    MockPublicKeyRecordRetriever mockPublicKeyRecordRetriever = new MockPublicKeyRecordRetriever(
            "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYDaYKXzwVYwqWbLhmuJ66aTAN8wmDR+rfHE8HfnkSOax0oIoTM5zquZrTLo30870YMfYzxwfB6j/Nz3QdwrUD/t0YMYJiUKyWJnCKfZXHJBJ+yfRHr7oW+UW3cVo9CG2bBfIxsInwYe175g9UjyntJpWueqdEIo1c2bhv9Mp66QIDAQAB;",
            "selector", "example.com");

    verify(rawMessage, mockPublicKeyRecordRetriever);
}
 
Example 17
Source File: MailService.java    From codenjoy with GNU General Public License v3.0 4 votes vote down vote up
public void sendEmail(String to, String title, String body) throws MessagingException {
        if (StringUtils.isEmpty(emailName)) {
            return;
        }
        String port = "465";

        Properties props = System.getProperties();
        props.put("mail.transport.protocol", "smtps");
        props.put("mail.smtp.host", "gc2.nodecluster.net");
//        props.put("mail.smtp.host", "mail.codenjoy.com");
//        props.put("mail.smtp.port", "26");
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true");
        props.setProperty("mail.smtp.ssl.trust", "gc2.nodecluster.net");
        props.put("mail.smtp.user", emailName);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.EnableSSL.enable", "true");
        props.put("mail.debug", "true");
        props.put("mail.password", emailPassword);
        props.put("mail.user", emailName);
        props.put("mail.from", emailName);
        props.put("mail.smtp.localhost", "codenjoy.com");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.socketFactory.port", port);

        // Get the default Session object.
        Session session = Session.getInstance(props, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailName, emailPassword);
            }
        });
//        session.setProtocolForAddress("rfc822", "smtps");

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(emailName));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(title);
        message.setContent(body, "text/html; charset=utf-8");
        Transport.send(message);
    }
 
Example 18
Source File: MailManager.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Send Emails to all the registered email id
 * 
 * @param emailData
 *                Instance of EmailData
 */
// Why a separate method & class EmailData needed??? 
private void processEmail(EmailData emailData) {
  boolean finerEnabled = logger.finerEnabled();
  if (finerEnabled) {
    logger.finer("Entered MailManager:processEmail");
  }

  if (mailHost == null || mailHost.length() == 0
      || emailData == null || mailToAddresses.length == 0) {
    if (logger.errorEnabled()) {
      logger.error(LocalizedStrings.MailManager_REQUIRED_MAILSERVER_CONFIGURATION_NOT_SPECIFIED);
    }
    if (logger.fineEnabled()) {
      logger.fine("Exited MailManager:processEmail: Not sending email as conditions not met");
    }
    return;
  }

  Session session = Session.getDefaultInstance(getMailHostConfiguration());
  MimeMessage mimeMessage = new MimeMessage(session);
  String subject = emailData.subject;
  String message = emailData.message;
  String mailToList = getMailToAddressesAsString();

  try {
    for (int i = 0; i < mailToAddresses.length; i++) {
      mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(
          mailToAddresses[i]));
    }

    if (subject == null) {
      subject = LocalizedStrings.MailManager_ALERT_MAIL_SUBJECT.toLocalizedString();
    }
    mimeMessage.setSubject(subject);

    if (message == null) {
      message = "";
    }
    mimeMessage.setText(message);

    Transport.send(mimeMessage);
    if (logger.infoEnabled()) {
      logger.info(
          LocalizedStrings.MailManager_EMAIL_ALERT_HAS_BEEN_SENT_0_1_2,
          new Object[] { mailToList, subject, message });
    }
  } catch (Throwable ex) {
    Error err;
    if (ex instanceof Error && SystemFailure.isJVMFailureError(
        err = (Error)ex)) {
      SystemFailure.initiateFailure(err);
      // If this ever returns, rethrow the error. We're poisoned
      // now, so don't let this thread continue.
      throw err;
    }
    // Whenever you catch Error or Throwable, you must also
    // check for fatal JVM error (see above).  However, there is
    // _still_ a possibility that you are dealing with a cascading
    // error condition, so you also need to check to see if the JVM
    // is still usable:
    SystemFailure.checkFailure();
    StringBuilder buf = new StringBuilder();
    buf.append(LocalizedStrings.MailManager_AN_EXCEPTION_OCCURRED_WHILE_SENDING_EMAIL.toLocalizedString());
    buf.append(LocalizedStrings.MailManager_UNABLE_TO_SEND_EMAIL_PLEASE_CHECK_YOUR_EMAIL_SETTINGS_AND_LOG_FILE.toLocalizedString());
    buf.append("\n\n").append(LocalizedStrings.MailManager_EXCEPTION_MESSAGE_0.toLocalizedString(ex.getMessage()));
    buf.append("\n\n").append(LocalizedStrings.MailManager_FOLLOWING_EMAIL_WAS_NOT_DELIVERED.toLocalizedString());
    buf.append("\n\t").append(LocalizedStrings.MailManager_MAIL_HOST_0.toLocalizedString(mailHost));
    buf.append("\n\t").append(LocalizedStrings.MailManager_FROM_0.toLocalizedString(mailFrom));
    buf.append("\n\t").append(LocalizedStrings.MailManager_TO_0.toLocalizedString(mailToList));
    buf.append("\n\t").append(LocalizedStrings.MailManager_SUBJECT_0.toLocalizedString(subject));
    buf.append("\n\t").append(LocalizedStrings.MailManager_CONTENT_0.toLocalizedString(message));

    logger.error(LocalizedStrings.ONE_ARG, buf.toString(), ex);
  }
  if (finerEnabled) {
    logger.finer("Exited MailManager:processEmail");
  }
}
 
Example 19
Source File: SendEmailController.java    From oncokb with GNU Affero General Public License v3.0 4 votes vote down vote up
private static Boolean sendFromGMail(String from, String pass, String[] to, String subject, String body) {
    Properties props = System.getProperties();
    String host = "smtp.gmail.com";
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");

    Session session = Session.getDefaultInstance(props);
    MimeMessage message = new MimeMessage(session);

    try {
        message.setFrom(new InternetAddress(from));
        InternetAddress[] toAddress = new InternetAddress[to.length];

        // To get the array of addresses
        for( int i = 0; i < to.length; i++ ) {
            toAddress[i] = new InternetAddress(to[i]);
        }

        for( int i = 0; i < toAddress.length; i++) {
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);
        }

        message.setSubject(subject);
        message.setText(body);
        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        return true;
    }
    catch (AddressException ae) {
        ae.printStackTrace();
    }
    catch (MessagingException me) {
        me.printStackTrace();
    }

    return false;
}
 
Example 20
Source File: JavaMailSender.java    From ogham with Apache License 2.0 2 votes vote down vote up
/**
 * Set the recipients addresses on the mime message.
 * 
 * @param email
 *            the source email
 * @param mimeMsg
 *            the mime message to fill
 * @throws MessagingException
 *             when the email address is not valid
 * @throws AddressException
 *             when the email address is not valid
 * @throws UnsupportedEncodingException
 *             when the email address is not valid
 */
private static void setRecipients(Email email, MimeMessage mimeMsg) throws MessagingException, UnsupportedEncodingException {
	for (Recipient recipient : email.getRecipients()) {
		mimeMsg.addRecipient(convert(recipient.getType()), toInternetAddress(recipient.getAddress()));
	}
}