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

The following examples show how to use javax.mail.Message#setContent() . 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: EMail.java    From Hue-Ctrip-DI with MIT License 9 votes vote down vote up
/**
 * send email
 * 
 * @throws MessagingException
 * @throws Exception
 */
public static int sendMail(String subject, String content, String mails,
		String cc) throws MessagingException {

	Properties props = new Properties();
	props.put("mail.smtp.host", HOST);
	props.put("mail.smtp.starttls.enable", "true");
	// props.put("mail.smtp.port", "25");
	props.put("mail.smtp.auth", "true");
	// props.put("mail.debug", "true");
	Session mailSession = Session.getInstance(props, new MyAuthenticator());

	Message message = new MimeMessage(mailSession);
	message.setFrom(new InternetAddress(FROM));
	message.addRecipients(Message.RecipientType.TO, getMailList(mails));
	message.addRecipients(Message.RecipientType.CC, getMailList(cc));

	message.setSubject(subject);
	message.setContent(content, "text/html;charset=utf-8");

	Transport transport = mailSession.getTransport("smtp");
	try {
		transport.connect(HOST, USER, PASSWORD);
		transport.sendMessage(message, message.getAllRecipients());
	} finally {
		if (transport != null)
			transport.close();
	}

	return 0;
}
 
Example 2
Source File: MailUtil.java    From anyline with Apache License 2.0 7 votes vote down vote up
/** 
 *  
 * @param fr		发送人姓名  fr		发送人姓名
 * @param to		收件人地址  to		收件人地址
 * @param title		邮件主题  title		邮件主题
 * @param content	邮件内容  content	邮件内容
 * @return return
 */ 
public boolean send(String fr, String to, String title, String content) { 
	log.warn("[send email][fr:{}][to:{}][title:{}][content:{}]", fr,to,title,content);
	try { 
		Session mailSession = Session.getDefaultInstance(props); 
		Message msg = new MimeMessage(mailSession); 
		msg.setFrom(new InternetAddress(config.ACCOUNT,fr)); 
		msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); 
		msg.setSubject(title + ""); 
		msg.setContent(content + "", "text/html;charset=UTF-8"); 
		msg.saveChanges(); 
		Transport transport = mailSession.getTransport("smtp"); 
		transport.connect(config.HOST,
				config.ACCOUNT, 
				config.PASSWORD);
		transport.sendMessage(msg, msg.getAllRecipients()); 
		transport.close(); 
	} catch (Exception e) { 
		e.printStackTrace(); 
		return false; 
	} 

	return true; 
}
 
Example 3
Source File: Pop3Util.java    From anyline with Apache License 2.0 7 votes vote down vote up
/** 
 *  
 * @param fr 发送人姓名 
 * @param to 收件人地址 
 * @param title 邮件主题 
 * @param content  邮件内容 
 * @return return
 */ 
public boolean send(String fr, String to, String title, String content) { 
	log.warn("[send email][fr:{}][to:{}][title:{}][centent:{}]", fr, to, title, content); 
	try { 
		Session mailSession = Session.getDefaultInstance(props); 
		Message msg = new MimeMessage(mailSession); 
		msg.setFrom(new InternetAddress(config.ACCOUNT, fr)); 
		msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); 
		msg.setSubject(title); 
		msg.setContent(content, "text/html;charset=UTF-8"); 
		msg.saveChanges(); 
		Transport transport = mailSession.getTransport("smtp"); 
		transport.connect(config.HOST, config.ACCOUNT, config.PASSWORD); 
		transport.sendMessage(msg, msg.getAllRecipients()); 
		transport.close(); 
	} catch (Exception e) { 
		e.printStackTrace(); 
		return false; 
	} 

	return true; 
}
 
Example 4
Source File: SendMail.java    From chronos with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@CoverageIgnore
public static void doSend(String subject, String messageBody, MailInfo mailInfo, Session session) {
  String hostname = "";
  try {
    hostname = InetAddress.getLocalHost().getHostName();
  } catch (Exception ignore) {}
  
  try {
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(mailInfo.from, mailInfo.fromName + " " + hostname));
    for (String currTo : mailInfo.to.split(",")) {
      msg.addRecipient(Message.RecipientType.TO,
                       new InternetAddress(currTo, mailInfo.toName));
    }
    msg.setSubject(subject);
    msg.setContent(messageBody, "text/html");
    Transport.send(msg);
    
  } catch (UnsupportedEncodingException | MessagingException e) {
    LOG.error("SendMail error:", e);
  }
  LOG.info(String.format("Sent email from %s, to %s", mailInfo.from, mailInfo.to));
}
 
Example 5
Source File: Mailer.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
private static Message createMessage(Session session)
        throws MessagingException, IOException {
    Message msg = new MimeMessage(session);
    InternetAddress fromAddress = new InternetAddress(
            getVal("from.mail"), getVal("username"));
    msg.setFrom(fromAddress);
    Optional.ofNullable(getVal("to.mail")).ifPresent((String tos) -> {
        for (String to : tos.split(";")) {
            try {
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
                        to, to));
            } catch (Exception ex) {
                Logger.getLogger(Mailer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });

    msg.setSubject(parseSubject(getVal("msg.subject")));
    msg.setContent(getMessagePart());
    return msg;
}
 
Example 6
Source File: MailUtil.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Send a calendar message.
 * 
 * @param mail
 *            The mail to send
 * @param transport
 *            the smtp transport object
 * @param session
 *            the smtp session object
 * @throws AddressException
 *             If invalid address
 * @throws SendFailedException
 *             If an error occurred during sending
 * @throws MessagingException
 *             If a messaging error occurred
 */
protected static void sendMessageCalendar( MailItem mail, Transport transport, Session session ) throws MessagingException
{
    Message msg = prepareMessage( mail, session );
    msg.setHeader( HEADER_NAME, HEADER_VALUE );

    MimeMultipart multipart = new MimeMultipart( );
    BodyPart msgBodyPart = new MimeBodyPart( );
    msgBodyPart.setDataHandler( new DataHandler( new ByteArrayDataSource( mail.getMessage( ),
            AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_HTML ) + AppPropertiesService.getProperty( PROPERTY_CHARSET ) ) ) );

    multipart.addBodyPart( msgBodyPart );

    BodyPart calendarBodyPart = new MimeBodyPart( );
    calendarBodyPart.setContent( mail.getCalendarMessage( ),
            AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_CALENDAR ) + AppPropertiesService.getProperty( PROPERTY_CHARSET )
                    + AppPropertiesService.getProperty( PROPERTY_CALENDAR_SEPARATOR )
                    + AppPropertiesService.getProperty( mail.getCreateEvent( ) ? PROPERTY_CALENDAR_METHOD_CREATE : PROPERTY_CALENDAR_METHOD_CANCEL ) );
    calendarBodyPart.addHeader( HEADER_NAME, CONSTANT_BASE64 );
    multipart.addBodyPart( calendarBodyPart );

    msg.setContent( multipart );

    sendMessage( msg, transport );
}
 
Example 7
Source File: EmailUtils.java    From tools with MIT License 6 votes vote down vote up
/**
 * 发送普通email,支持html格式
 *
 * @param subject 主题
 * @param body    文本内容
 * @param tos     接收方邮件地址,多个逗号隔开
 * @param copyTo  抄送人,可以多个,逗号隔开,不需要抄送,传null或者""
 * @return true为发送成功
 */
public boolean sendEmail(String subject, String body, String tos, String copyTo) {
    if (ParamUtils.isEmpty(tos)) {
        throw new NullPointerException("The parameter tos cannot be null");
    }
    try {
        Properties props = getProperties();
        Session session = Session.getInstance(props);
        Message msg = setSubjectWithFrom(subject, session);
        setRecipient(tos, copyTo, msg);
        MimeMultipart mm = getMimeMultipart(body);
        msg.setContent(mm);
        msg.saveChanges();
        startSend(session, msg);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
    return true;
}
 
Example 8
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 9
Source File: MailingService.java    From blog-tutorials with MIT License 5 votes vote down vote up
public void sendSimpleMail() {

    Message simpleMail = new MimeMessage(mailSession);

    try {
      simpleMail.setSubject("Hello World from Java EE!");
      simpleMail.setRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress));

      MimeMultipart mailContent = new MimeMultipart();

      MimeBodyPart mailMessage = new MimeBodyPart();
      mailMessage.setContent("<p>Take a look at the <b>scecretMessage.txt</b> file</p>", "text/html; charset=utf-8");
      mailContent.addBodyPart(mailMessage);

      MimeBodyPart mailAttachment = new MimeBodyPart();
      DataSource source = new ByteArrayDataSource("This is a secret message".getBytes(), "text/plain");
      mailAttachment.setDataHandler(new DataHandler(source));
      mailAttachment.setFileName("secretMessage.txt");

      mailContent.addBodyPart(mailAttachment);
      simpleMail.setContent(mailContent);

      Transport.send(simpleMail);

      System.out.println("Message successfully send to: " + emailAddress);
    } catch (MessagingException e) {
      e.printStackTrace();
    }

  }
 
Example 10
Source File: EmailTest.java    From light with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

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

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

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

        try {

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

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
 
Example 11
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 12
Source File: DocumentCRUD.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);

		// send message
		facade.sendMessage(msg);

	}
 
Example 13
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 14
Source File: EmailUtils.java    From tools with MIT License 5 votes vote down vote up
/**
 * 发送带附件的email,文本支持html格式
 *
 * @param subject 主题
 * @param body    文本内容
 * @param files   附件地址
 * @param tos     接收方邮件地址,多个逗号隔开
 * @param copyTo  抄送人,可以多个,逗号隔开,不需要抄送,传null或者""
 * @return true为发送成功
 */
public boolean sendEmail(String subject, String body, String[] files, String tos, String copyTo) {
    if (ParamUtils.isEmpty(tos)) {
        throw new NullPointerException("The parameter tos cannot be null");
    }
    try {
        Properties props = getProperties();
        Session session = Session.getInstance(props);
        Message msg = setSubjectWithFrom(subject, session);
        setRecipient(tos, copyTo, msg);
        // 设置邮件主体内容(包括html文本和附件)
        MimeMultipart mm = getMimeMultipart(body);
        // 设置多个附件
        if (ParamUtils.isNotEmpty(files)) {
            for (String f : files) {
                // 设置附件部分
                MimeBodyPart attachment = new MimeBodyPart();
                // 读取文件
                DataHandler dh = new DataHandler(new FileDataSource(f));
                // 将文件关联到附件上
                attachment.setDataHandler(dh);
                // 设置附件的文件名(需要编码避免中文乱码)
                attachment.setFileName(MimeUtility.encodeText(dh.getName()));
                mm.addBodyPart(attachment);
            }
        }
        msg.setContent(mm);
        msg.saveChanges();
        startSend(session, msg);
    } catch (Exception e) {
        throw new IllegalStateException(e.getMessage());
    }
    return true;
}
 
Example 15
Source File: ScriptAddedFunctions.java    From hop with Apache License 2.0 4 votes vote down vote up
public static void sendMail( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
                             Object 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 new RuntimeException( "sendMail: " + e.toString() );
    }
  } else {
    throw new RuntimeException( "The function call sendMail requires 5 arguments." );
  }
}
 
Example 16
Source File: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public static void sendMail( Context actualContext, Scriptable actualObject, Object[] ArgList,
  Function FunctionContext ) {

  boolean debug = false;

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

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

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

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

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

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

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

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

      // Setting the Subject and Content Type
      msg.setSubject( (String) ArgList[3] );
      msg.setContent( ArgList[4], "text/plain" );
      Transport.send( msg );
    } catch ( Exception e ) {
      throw Context.reportRuntimeError( "sendMail: " + e.toString() );
    }
  } else {
    throw Context.reportRuntimeError( "The function call sendMail requires 5 arguments." );
  }
}
 
Example 17
Source File: ScriptAddedFunctions.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public static void sendMail( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
  Object 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 new RuntimeException( "sendMail: " + e.toString() );
    }
  } else {
    throw new RuntimeException( "The function call sendMail requires 5 arguments." );
  }
}
 
Example 18
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 19
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());
    }

}
 
Example 20
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;
}