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

The following examples show how to use javax.mail.Message#setSentDate() . 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: NotifierBean.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
private void sendEmail(String email, String name, String subject, String content) throws MessagingException {

        if (email == null || email.isEmpty()) {
            LOGGER.log(Level.WARNING, "Cannot send mail, email is empty");
            return;
        }

        try {
            InternetAddress emailAddress = new InternetAddress(email, name);
            Message message = new MimeMessage(mailSession);
            message.addRecipient(Message.RecipientType.TO, emailAddress);
            message.setSubject(subject);
            message.setSentDate(new Date());
            message.setContent(content, "text/html; charset=utf-8");
            message.setFrom();
            Transport.send(message);
        } catch (UnsupportedEncodingException e) {
            String logMessage = "Unsupported encoding: " + e.getMessage();
            LOGGER.log(Level.SEVERE, logMessage, e);
        }
    }
 
Example 2
Source File: MailServerImpl.java    From webcurator with Apache License 2.0 6 votes vote down vote up
public void send(Mailable email) throws MessagingException {
    Session mailSession = Session.getInstance(this.mailConfig, null);
    Message message = new MimeMessage(mailSession);

    message.setFrom(new InternetAddress(email.getSender()));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(email.getRecipients()));
    setUpCCandBCC(email, message);

    if(email.getReplyTo()!=null && email.getReplyTo().trim().length()!=0) {
        message.setReplyTo(new Address[] {new InternetAddress(email.getReplyTo())});
    }

    message.setSubject(email.getSubject());
    message.setSentDate(new Date());
    message.setContent(email.getMessage(), "text/plain; charset=UTF-8");

    Transport.send(message); 
}
 
Example 3
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 4
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 5
Source File: EmailNotificationService.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void notify(final NotificationContext context, final NotificationType notificationType, final String subject, final String messageText) throws NotificationFailedException {
    final Properties properties = getMailProperties(context);
    final Session mailSession = createMailSession(properties);
    final Message message = new MimeMessage(mailSession);

    try {
        message.setFrom(InternetAddress.parse(context.getProperty(FROM).evaluateAttributeExpressions().getValue())[0]);

        final InternetAddress[] toAddresses = toInetAddresses(context.getProperty(TO).evaluateAttributeExpressions().getValue());
        message.setRecipients(RecipientType.TO, toAddresses);

        final InternetAddress[] ccAddresses = toInetAddresses(context.getProperty(CC).evaluateAttributeExpressions().getValue());
        message.setRecipients(RecipientType.CC, ccAddresses);

        final InternetAddress[] bccAddresses = toInetAddresses(context.getProperty(BCC).evaluateAttributeExpressions().getValue());
        message.setRecipients(RecipientType.BCC, bccAddresses);

        message.setHeader("X-Mailer", context.getProperty(HEADER_XMAILER).evaluateAttributeExpressions().getValue());
        message.setSubject(subject);

        final String contentType = context.getProperty(CONTENT_TYPE).evaluateAttributeExpressions().getValue();
        message.setContent(messageText, contentType);
        message.setSentDate(new Date());

        Transport.send(message);
    } catch (final ProcessException | MessagingException e) {
        throw new NotificationFailedException("Failed to send E-mail Notification", e);
    }
}
 
Example 6
Source File: SimpleMailSender.java    From disconf with Apache License 2.0 5 votes vote down vote up
/**
 * @param mailInfo
 *
 * @return
 */
private static Message setCommon(MailSenderInfo mailInfo) throws MessagingException {

    //
    // 判断是否需要身份认证
    //
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
        // 如果需要身份认证,则创建一个密码验证器
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }

    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session sendMailSession = Session.getDefaultInstance(pro, authenticator);

    // 根据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());

    return mailMessage;

}
 
Example 7
Source File: SimpleMailSender.java    From disconf with Apache License 2.0 5 votes vote down vote up
/**
 * @param mailInfo
 *
 * @return
 */
private static Message setCommon(MailSenderInfo mailInfo) throws MessagingException {

    //
    // 判断是否需要身份认证
    //
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
        // 如果需要身份认证,则创建一个密码验证器
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }

    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session sendMailSession = Session.getDefaultInstance(pro, authenticator);

    // 根据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());

    return mailMessage;

}
 
Example 8
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 9
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 10
Source File: AbstractMailSenderFactory.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 以HTML格式发送邮件.
 *
 * @param mailSender 待发送的邮件信息
 * @return Boolean
 */
protected boolean sendHtmlMail(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());
        final Multipart mainPart = new MimeMultipart();
        final BodyPart html = new MimeBodyPart();
        html.setContent(mailSender.getContent(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        mailMessage.setContent(mainPart);
        Transport.send(mailMessage);
        return true;
    } catch (final MessagingException ex) {
        LOGGER.error(ex.getMessage(), ex);
    }
    
    return false;
}
 
Example 11
Source File: MailSender.java    From SensorWebClient with GNU General Public License v2.0 5 votes vote down vote up
public static boolean sendEmailValidationMail(String address, String userID) {
    LOGGER.debug("send email validation mail to: " + address);

    String link = "?validate=" + userID;
    String text = SesConfig.mailTextValidation_en + ": " + "\n" +
    SesConfig.mailTextValidation_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
        msg.setSubject(SesConfig.mailSubjectValidation_en + "/" + SesConfig.mailSubjectValidation_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 email validation mail: " + e.getMessage(), e);
    }
    return false;
}
 
Example 12
Source File: ExceptionNotificationServiceImpl.java    From telekom-workflow-engine with MIT License 5 votes vote down vote up
private void sendEmail( String from, String to, String subject, String body ){
    log.info( "Sending exception email from:{} to:{} subject:{}", from, to, subject );
    try{
        Properties props = new Properties();
        props.put( "mail.smtp.host", smtpHost );
        if (StringUtils.isNotBlank(smtpPort)) {
            props.put( "mail.smtp.port", smtpPort );
        }
        Authenticator authenticator = null;
        if (StringUtils.isNotBlank(smtpUsername)) {
            props.put( "mail.smtp.auth", true );
            authenticator = new SmtpAuthenticator();
        }
        Session session = Session.getDefaultInstance( props, authenticator );

        Message msg = new MimeMessage( session );
        msg.setFrom( new InternetAddress( from ) );

        InternetAddress[] addresses = InternetAddress.parse( to );
        msg.setRecipients( Message.RecipientType.TO, addresses );

        msg.setSubject( subject );
        msg.setSentDate( new Date() );
        msg.setText( body );
        Transport.send( msg );
    }
    catch( Exception e ){
        log.warn( "Sending email failed: ", e );
    }
}
 
Example 13
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 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: MailSender.java    From SensorWebClient with GNU General Public License v2.0 5 votes vote down vote up
public static void sendPasswordMail(String address, String newPassword) {
    LOGGER.debug("send new password to: " + address);

    final String text = SesConfig.mailTextPassword_en + ": " + "\n\n" +
    SesConfig.mailTextPassword_de + ": " + "\n\n" + newPassword;

    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.mailSubjectPassword_en + "/" + SesConfig.mailSubjectPassword_de);
        msg.setText(text);
        msg.setSentDate(new Date());

        // send mail
        Transport.send(msg);
        LOGGER.debug("mail send succesfully done");
    } catch (Exception e) {
        LOGGER.error("Error occured while sending password mail: " + e.getMessage(), e);
    }
}
 
Example 16
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 17
Source File: SendEMail.java    From tn5250j with GNU General Public License v2.0 4 votes vote down vote up
/**
 * This method processes the send request from the compose form
 */
public boolean send() throws Exception {

   try {
      if(!loadConfig(configFile))
         return false;

      Session session = Session.getDefaultInstance(SMTPProperties, null);
      session.setDebug(false);

      // create the Multipart and its parts to it
      Multipart mp = new MimeMultipart();

      Message msg = new MimeMessage(session);
      InternetAddress[] toAddrs = null, ccAddrs = null;

      toAddrs = InternetAddress.parse(to, false);
      msg.setRecipients(Message.RecipientType.TO, toAddrs);

      if (cc != null) {
         ccAddrs = InternetAddress.parse(cc, false);
         msg.setRecipients(Message.RecipientType.CC, ccAddrs);
      }

      if (subject != null)
         msg.setSubject(subject.trim());

      if (from == null)
         from = SMTPProperties.getProperty("mail.smtp.from");

      if (from != null && from.length() > 0) {
      	pers = SMTPProperties.getProperty("mail.smtp.realname");
      	if (pers != null) msg.setFrom(new InternetAddress(from, pers));
      }

      if (message != null && message.length() > 0) {
         // create and fill the attachment message part
         MimeBodyPart mbp = new MimeBodyPart();
         mbp.setText(message,"us-ascii");
         mp.addBodyPart(mbp);
      }

      msg.setSentDate(new Date());

      if (attachment != null && attachment.length() > 0) {
         // create and fill the attachment message part
         MimeBodyPart abp = new MimeBodyPart();

         abp.setText(attachment,"us-ascii");

         if (attachmentName == null || attachmentName.length() == 0)
            abp.setFileName("tn5250j.txt");
         else
            abp.setFileName(attachmentName);
         mp.addBodyPart(abp);

      }

      if (fileName != null && fileName.length() > 0) {
         // create and fill the attachment message part
         MimeBodyPart fbp = new MimeBodyPart();

         fbp.setText("File sent using tn5250j","us-ascii");

         if (attachmentName == null || attachmentName.length() == 0) {
            	fbp.setFileName("tn5250j.txt");
         }
         else
            fbp.setFileName(attachmentName);

          // Get the attachment
          DataSource source = new FileDataSource(fileName);

          // Set the data handler to the attachment
          fbp.setDataHandler(new DataHandler(source));

         mp.addBodyPart(fbp);

      }

      // add the Multipart to the message
      msg.setContent(mp);

      // send the message
      Transport.send(msg);
      return true;
   }
   catch (SendFailedException sfe) {
      showFailedException(sfe);
   }
   return false;
}
 
Example 18
Source File: SimpleMailSender.java    From KJFrameForAndroid with Apache License 2.0 4 votes vote down vote up
/**
 * 以HTML格式发送邮件
 * 
 * @param mailInfo
 *            待发送的邮件信息
 */
public static boolean sendHtmlMail(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());
        // Message.RecipientType.TO属性表示接收者的类型为TO
        mailMessage.setRecipient(Message.RecipientType.TO, to);
        // 设置邮件消息的主题
        mailMessage.setSubject(mailInfo.getSubject());
        // 设置邮件消息发送的时间
        mailMessage.setSentDate(new Date());
        // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
        Multipart mainPart = new MimeMultipart();
        // 创建一个包含HTML内容的MimeBodyPart
        BodyPart html = new MimeBodyPart();
        // 设置HTML内容
        html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        // 将MiniMultipart对象设置为邮件内容
        mailMessage.setContent(mainPart);
        // 发送邮件
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
    return false;
}
 
Example 19
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 20
Source File: SendEmailSmtp.java    From opentest with MIT License 4 votes vote down vote up
@Override
public void run() {
    String server = this.readStringArgument("server");
    String subject = this.readStringArgument("subject");
    String body = this.readStringArgument("body");
    String userName = this.readStringArgument("userName");
    String password = this.readStringArgument("password");
    String to = this.readStringArgument("to");
    Integer port = this.readIntArgument("port", 25);
    Boolean useTls = this.readBooleanArgument("useTls", true);
    String cc = this.readStringArgument("cc", null);
    String from = this.readStringArgument("from", "[email protected]");

    try {
        Properties prop = System.getProperties();
        prop.put("mail.smtp.host", server);
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.port", port.toString());

        Session session = Session.getInstance(prop, null);
        Message msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(from));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));

        if (cc != null) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }

        msg.setSubject(subject);
        msg.setText(body);
        msg.setSentDate(new Date());

        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
        transport.setStartTLS(useTls);
        transport.connect(server, userName, password);
        transport.sendMessage(msg, msg.getAllRecipients());

        transport.close();
    } catch (Exception exc) {
        throw new RuntimeException("Failed to send email", exc);
    }
}