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

The following examples show how to use javax.mail.Message#setSubject() . 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: 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: JavaMail.java    From EasyML with Apache License 2.0 6 votes vote down vote up
public boolean sendMsg(String recipient, String subject, String content)
		throws MessagingException {
	// Create a mail object
	Session session = Session.getInstance(props, new Authenticator() {
		// Set the account information session,transport will send mail
		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(Constants.MAIL_USERNAME, Constants.MAIL_PASSWORD);
		}
	});
	session.setDebug(true);
	Message msg = new MimeMessage(session);
	try {
		msg.setSubject(subject);			//Set the mail subject
		msg.setContent(content,"text/html;charset=utf-8");
		msg.setFrom(new InternetAddress(Constants.MAIL_USERNAME));			//Set the sender
		msg.setRecipient(RecipientType.TO, new InternetAddress(recipient));	//Set the recipient
		Transport.send(msg);
		return true;
	} catch (Exception ex) {
		ex.printStackTrace();
		System.out.println(ex.getMessage());
		return false;
	}

}
 
Example 4
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 5
Source File: Signup.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private void sendMail(String emailAddress, String subject, String emailContent) throws Exception {

		SessionFacade facade = MailSessionBuilder.newInstance()
			.usingUserProfile()
			.withTimeout(5000)
			.withConnectionTimeout(5000)
			.build();

		// create a message
		Message msg = facade.createNewMimeMessage();

		InternetAddress addressTo = new InternetAddress(emailAddress);

		msg.setRecipient(Message.RecipientType.TO, addressTo);

		// Setting the Subject and Content Type
		msg.setSubject(subject);
		// create and fill the first message part
		// MimeBodyPart mbp1 = new MimeBodyPart();
		// mbp1.setText(emailContent);
		// // create the Multipart and add its parts to it
		// Multipart mp = new MimeMultipart();
		// mp.addBodyPart(mbp1);
		// // add the Multipart to the message
		// msg.setContent(mp);
		msg.setContent(emailContent, "text/html");

		// send message
		facade.sendMessage(msg);

	}
 
Example 6
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 7
Source File: EmailNotificationService.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void notify(final NotificationContext context, 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 8
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 9
Source File: MailSenderUtil.java    From kardio with Apache License 2.0 5 votes vote down vote up
/**
 * Send Mail Alert.
 * 
 * @param Message
 */
public static void sendMail(String messageText, String toMail, String subject){
	
	Properties props = new Properties();
	props.put("mail.smtp.starttls.enable", "true");
       props.put("mail.smtp.host", propertyUtil.getValue(SurveillerConstants.MAIL_SERVER_IP));
       props.put("mail.smtp.port", propertyUtil.getValue(SurveillerConstants.MAIL_SERVER_PORT));
       Session session = null;
       String mailAuthUserName = propertyUtil.getValue(SurveillerConstants.MAIL_SERVER_USERNAME);
       String mailAuthPassword = propertyUtil.getValue(SurveillerConstants.MAIL_SERVER_PASSWORD);
	if (mailAuthUserName != null && mailAuthUserName.length() > 0 && mailAuthPassword != null
			&& mailAuthPassword.length() > 0) {
		props.put("mail.smtp.auth", "true");
		Authenticator auth = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(mailAuthUserName, mailAuthPassword);
			}
		};
		session = Session.getDefaultInstance(props, auth);
	} else {
		props.put("mail.smtp.auth", "false");
		session = Session.getInstance(props);
	}
	
	try {
		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress(propertyUtil.getValue(SurveillerConstants.MAIL_FROM_ADDRESS) ));
		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toMail));
		message.setSubject(subject);
		message.setText(messageText);
		Transport.send(message);
	} catch (MessagingException me) {
		logger.error("Error in Mail Sending: " +  me);
		throw new RuntimeException(me.getMessage());
	}

	logger.debug("Mail Sent to: " + toMail);
}
 
Example 10
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 11
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 12
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 13
Source File: TestMailClient.java    From holdmail with Apache License 2.0 5 votes vote down vote up
public void sendResourceEmail(String resourceName, String sender, String recipient, String subjectOverride) {

        try {

            InputStream resource = TestMailClient.class.getClassLoader().getResourceAsStream(resourceName);
            if (resource == null) {
                throw new MessagingException("Couldn't find resource at: " + resourceName);
            }

            Message message = new MimeMessage(session, resource);

            // 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[] {});

            // then set the new data
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
            message.setFrom(InternetAddress.parse(sender)[0]);

            if(StringUtils.isNotBlank(subjectOverride)) {
                message.setSubject(subjectOverride);
            }

            Transport.send(message);

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

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

    }
 
Example 14
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 15
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 16
Source File: EmailNotification.java    From oodt with Apache License 2.0 5 votes vote down vote up
@Override
public boolean performAction(File product, Metadata metadata)
      throws CrawlerActionException {
   try {
      Properties props = new Properties();
      props.put("mail.host", this.mailHost);
      props.put("mail.transport.protocol", "smtp");
      props.put("mail.from", this.sender);

      Session session = Session.getDefaultInstance(props);
      Message msg = new MimeMessage(session);
      msg.setSubject(PathUtils.doDynamicReplacement(subject, metadata));
      msg.setText(new String(PathUtils.doDynamicReplacement(message,
            metadata).getBytes()));
      for (String recipient : recipients) {
         try {
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
                  PathUtils.replaceEnvVariables(recipient.trim(), metadata),
                  ignoreInvalidAddresses));
            LOG.fine("Recipient: "
                  + PathUtils.replaceEnvVariables(recipient.trim(), metadata));
         } catch (AddressException ae) {
            LOG.fine("Recipient: "
                  + PathUtils.replaceEnvVariables(recipient.trim(), metadata));
            LOG.warning(ae.getMessage());
         }
      }
      LOG.fine("Subject: " + msg.getSubject());
      LOG.fine("Message: "
            + new String(PathUtils.doDynamicReplacement(message, metadata)
                  .getBytes()));
      Transport.send(msg);
      return true;
   } catch (Exception e) {
      LOG.severe(e.getMessage());
      return false;
   }
}
 
Example 17
Source File: MailManager.java    From Cynthia with GNU General Public License v2.0 4 votes vote down vote up
/**
	 * @description:send mail
	 * @date:2014-5-6 下午12:11:34
	 * @version:v1.0
	 * @param subject:mail subject
	 * @param recievers:mail recievers
	 * @param content:mail content
	 * @return:if mail send success
	 */
	public static boolean sendMail(String fromUser, String subject,String[] recievers,String content){
        try{
            Properties props = ConfigManager.getEmailProperties();
            
            //配置中定义不发送邮件
            if (props.getProperty("mail.enable") == null || !props.getProperty("mail.enable").equals("true")) {
				System.out.println("there is a mail not send by config!");
            	return true;
			}
            
            //创建一个程序与邮件服务器的通信
            Session mailConnection = Session.getInstance(props,null);
            Message msg = new MimeMessage(mailConnection);
                                
            //设置发送人和接受人
            Address sender = new InternetAddress(props.getProperty("mail.user"));
            //单个接收人
            //Address receiver = new InternetAddress("[email protected]");
            //多个接收人
            StringBuffer buffer = new StringBuffer();
            for (String reciever : recievers) {
				buffer.append(buffer.length() > 0 ? ",":"").append(reciever);
			}
            String all = buffer.toString();
            System.out.println("send Mail,mailList:" + all);
            
            msg.setFrom(sender);
            Set<InternetAddress> toUserSet = new HashSet<InternetAddress>();
            //邮箱有效性较验
            for (int i = 0; i < recievers.length; i++) {
                if(recievers[i].trim().matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)+$")){
                	toUserSet.add(new InternetAddress(recievers[i].trim()));
                }
            }
            
            msg.setRecipients(Message.RecipientType.TO, toUserSet.toArray(new InternetAddress[0]));
            
            //设置邮件主题
            msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));   //中文乱码问题
            
            //设置邮件内容
            BodyPart messageBodyPart = new MimeBodyPart(); 
            messageBodyPart.setContent( content, "text/html; charset=utf-8" ); // 中文
            Multipart multipart = new MimeMultipart(); 
            multipart.addBodyPart( messageBodyPart ); 
            msg.setContent(multipart);
                                
            /**********************发送附件************************/
//	            //新建一个MimeMultipart对象用来存放多个BodyPart对象
//	            Multipart mtp=new MimeMultipart();
//	            //------设置信件文本内容------
//	            //新建一个存放信件内容的BodyPart对象
//	            BodyPart mdp=new MimeBodyPart();
//	            //给BodyPart对象设置内容和格式/编码方式
//	            mdp.setContent("hello","text/html;charset=gb2312");
//	            //将含有信件内容的BodyPart加入到MimeMultipart对象中
//	            mtp.addBodyPart(mdp);
//	                                
//	            //设置信件的附件(用本地机上的文件作为附件)
//	            mdp=new MimeBodyPart();
//	            FileDataSource fds=new FileDataSource("f:/webservice.doc");
//	            DataHandler dh=new DataHandler(fds);
//	            mdp.setFileName("webservice.doc");//可以和原文件名不一致
//	            mdp.setDataHandler(dh);
//	            mtp.addBodyPart(mdp);
//	            //把mtp作为消息对象的内容
//	            msg.setContent(mtp);
           /**********************发送附件结束************************/  

            //先进行存储邮件
            msg.saveChanges();
            Transport trans = mailConnection.getTransport(props.getProperty("mail.protocal"));
            //邮件服务器名,用户名,密码
            trans.connect(props.getProperty("mail.smtp.host"), props.getProperty("mail.user"),  props.getProperty("mail.pass"));
            trans.sendMessage(msg, msg.getAllRecipients());
            
            //关闭通道
            if (trans.isConnected()) {
            	trans.close();
			}
            return true;
        }catch(Exception e)
        {
            System.err.println(e);
            return false;
        }
        finally{
        }
	}
 
Example 18
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 19
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);
    }
}
 
Example 20
Source File: mailer.java    From SocietyPoisonerTrojan with GNU General Public License v3.0 4 votes vote down vote up
public void sendMail (
        String server,
        String from, String to,
        String subject, String text,
        final String login,
        final String password,
        String filename
                      )
{
    Properties properties = new Properties();
    properties.put ("mail.smtp.host", server);
    properties.put ("mail.smtp.socketFactory.port", "465");
    properties.put ("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    properties.put ("mail.smtp.auth", "true");
    properties.put ("mail.smtp.port", "465");

    try {
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(login, password);
            }
        });

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress (to));
        message.setSubject(subject);

        Multipart multipart = new MimeMultipart ();
        BodyPart bodyPart = new MimeBodyPart ();

        bodyPart.setContent (text, "text/html; charset=utf-8");
        multipart.addBodyPart (bodyPart);

        if (filename != null) {
            bodyPart.setDataHandler (new DataHandler (new FileDataSource (filename)));
            bodyPart.setFileName (filename);

            multipart.addBodyPart (bodyPart);
        }

        message.setContent(multipart);

        Transport.send(message);
    } catch (Exception e) {
        Log.e ("Send Mail Error!", e.getMessage());
    }

}