javax.mail.Session#setDebug ( )源码实例Demo

下面列出了javax.mail.Session#setDebug ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: smart-admin   文件: SmartSendMailUtil.java
/**
 * 创建session
 *
 * @author lidoudou
 * @date 2019/2/16 14:59
 */
private static Session createSession(String sendSMTPHost) {
    // 1. 创建参数配置, 用于连接邮件服务器的参数配置
    Properties props = new Properties(); // 参数配置
    props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求)
    props.setProperty("mail.smtp.host", sendSMTPHost); // 发件人的邮箱的 SMTP 服务器地址
    props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
    // PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启),
    // 如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误,
    // 打开下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。
    /*
     * // SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接, // 需要改为对应邮箱的 SMTP 服务器的端口,
     * 具体可查看对应邮箱服务的帮助, // QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看) final String smtpPort = "465";
     * props.setProperty("mail.smtp.port", smtpPort);
     * props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
     * props.setProperty("mail.smtp.socketFactory.fallback", "false");
     * props.setProperty("mail.smtp.socketFactory.port", smtpPort);
     */
    // 2. 根据配置创建会话对象, 用于和邮件服务器交互
    Session session = Session.getInstance(props);
    session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log
    return session;
}
 
源代码2 项目: olat   文件: MailHelper.java
/**
    * Create a configures mail message object that is ready to use
    * 
    * @return MimeMessage
    */
static MimeMessage createMessage() {
       Properties p = new Properties();
       p.put("mail.smtp.host", mailhost);
       p.put("mail.smtp.timeout", mailhostTimeout);
       p.put("mail.smtp.connectiontimeout", mailhostTimeout);
       p.put("mail.smtp.ssl.enable", sslEnabled);
       p.put("mail.smtp.ssl.checkserveridentity", sslCheckCertificate);
       Session mailSession;
       if (smtpAuth == null) {
           mailSession = javax.mail.Session.getInstance(p);
       } else {
           // use smtp authentication from configuration
           p.put("mail.smtp.auth", "true");
           mailSession = Session.getDefaultInstance(p, smtpAuth);
       }
       if (log.isDebugEnabled()) {
           // enable mail session debugging on console
           mailSession.setDebug(true);
       }
       return new MimeMessage(mailSession);
   }
 
public static boolean sendemail(String theme, String messages,String email){
	Properties prop = new Properties();
	prop.put("mail.transport.protocol", "smtp");
	prop.put("mail.host", "smtp.163.com");
	prop.put("mail.smtp.auth", "true");
	Session session = Session.getInstance(prop);
	session.setDebug(true);
	Message message;
	try {
		message = createSimpleMail(session, theme, messages,email);
		Transport ts = session.getTransport();
		ts.connect("[email protected]", "12345678910");
		ts.sendMessage(message, message.getAllRecipients());
		ts.close();
		return true;
	} catch (Exception e) {
		return false;
	}
	
}
 
源代码4 项目: EasyML   文件: JavaMail.java
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;
	}

}
 
private static void sendMail()
        throws MessagingException, IOException {
    Session session = Session.getInstance(getMailProps(), new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(
                    getVal("username"),
                    getVal("password"));
        }
    });
    session.setDebug(getBoolVal("mail.debug"));
    LOG.info("Compiling Mail before Sending");
    Message message = createMessage(session);
    Transport transport = session.getTransport("smtp");
    LOG.info("Connecting to Mail Server");
    transport.connect();
    LOG.info("Sending Mail");
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
    LOG.info("Reports are sent to Mail");
    clearTempZips();
}
 
源代码6 项目: logging-log4j2   文件: SmtpManager.java
@Override
public SmtpManager createManager(final String name, final FactoryData data) {
    final String prefix = "mail." + data.protocol;

    final Properties properties = PropertiesUtil.getSystemProperties();
    properties.setProperty("mail.transport.protocol", data.protocol);
    if (properties.getProperty("mail.host") == null) {
        // Prevent an UnknownHostException in Java 7
        properties.setProperty("mail.host", NetUtils.getLocalHostname());
    }

    if (null != data.host) {
        properties.setProperty(prefix + ".host", data.host);
    }
    if (data.port > 0) {
        properties.setProperty(prefix + ".port", String.valueOf(data.port));
    }

    final Authenticator authenticator = buildAuthenticator(data.username, data.password);
    if (null != authenticator) {
        properties.setProperty(prefix + ".auth", "true");
    }

    if (data.protocol.equals("smtps")) {
        final SslConfiguration sslConfiguration = data.sslConfiguration;
        if (sslConfiguration != null) {
            final SSLSocketFactory sslSocketFactory = sslConfiguration.getSslSocketFactory();
            properties.put(prefix + ".ssl.socketFactory", sslSocketFactory);
            properties.setProperty(prefix + ".ssl.checkserveridentity", Boolean.toString(sslConfiguration.isVerifyHostName()));
        }
    }

    final Session session = Session.getInstance(properties, authenticator);
    session.setProtocolForAddress("rfc822", data.protocol);
    session.setDebug(data.isDebug);
    return new SmtpManager(name, session, null, data);
}
 
源代码7 项目: tomee   文件: EmailService.java
@POST
public String lowerCase(final String message) {

    try {

        //Create some properties and get the default Session
        final Properties props = new Properties();
        props.put("mail.smtp.host", "your.mailserver.host");
        props.put("mail.debug", "true");

        final Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("MyUsername", "MyPassword");
            }
        });

        //Set this just to see some internal logging
        session.setDebug(true);

        //Create a message
        final MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("[email protected]"));
        final InternetAddress[] address = {new InternetAddress("[email protected]")};
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject("JavaMail API test");
        msg.setSentDate(new Date());
        msg.setText(message, "UTF-8");


        Transport.send(msg);
    } catch (final MessagingException e) {
        return "Failed to send message: " + e.getMessage();
    }

    return "Sent";
}
 
源代码8 项目: hellokoding-courses   文件: SendingMailService.java
private boolean sendMail(String toEmail, String subject, String body) {
    try {
        Properties props = System.getProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.port", mailProperties.getSmtp().getPort());
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);
        session.setDebug(true);

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(mailProperties.getFrom(), mailProperties.getFromName()));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        msg.setSubject(subject);
        msg.setContent(body, "text/html");

        Transport transport = session.getTransport();
        transport.connect(mailProperties.getSmtp().getHost(), mailProperties.getSmtp().getUsername(), mailProperties.getSmtp().getPassword());
        transport.sendMessage(msg, msg.getAllRecipients());
        return true;
    } catch (Exception ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getMessage(), ex);
    }

    return false;
}
 
源代码9 项目: lemon   文件: JavamailService.java
public void send(String to, String cc, String bcc, String subject,
        String content, JavamailConfig javamailConfig)
        throws MessagingException {
    logger.debug("send : {}, {}", to, subject);

    try {
        Properties props = createSmtpProperties(javamailConfig);
        String username = javamailConfig.getUsername();
        String password = javamailConfig.getPassword();

        // 创建Session实例对象
        Session session = Session.getInstance(props, new SmtpAuthenticator(
                username, password));
        session.setDebug(false);

        // 创建MimeMessage实例对象
        MimeMessage message = new MimeMessage(session);
        // 设置邮件主题
        message.setSubject(subject);
        // 设置发送人
        message.setFrom(new InternetAddress(username));
        // 设置发送时间
        message.setSentDate(new Date());
        // 设置收件人
        message.setRecipients(RecipientType.TO, InternetAddress.parse(to));
        // 设置html内容为邮件正文,指定MIME类型为text/html类型,并指定字符编码为gbk
        message.setContent(content, "text/html;charset=gbk");

        // 保存并生成最终的邮件内容
        message.saveChanges();

        // 发送邮件
        Transport.send(message);
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}
 
源代码10 项目: mail-micro-service   文件: MailManager.java
public static void putBoth(String key, Properties properties){
    putProperties(key, properties);
    // 此处要用 Session#getInstance,Session#getDefaultInstance 为单例
    Session session = Session.getInstance(properties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(properties.getProperty("mail.username"),
                    properties.getProperty("mail.password"));
        }
    });
    if(null != properties.getProperty("mail.debug")){
        session.setDebug(Boolean.valueOf(properties.getProperty("mail.debug")));
    }
    putSession(key, session);
}
 
源代码11 项目: jforgame   文件: EMailManager.java
/**
 * 同步发送邮件
 * @param title
 * @param content
 */
public void sendEmailSync(String title, String content) {
	try { // 1. 创建参数配置, 用于连接邮件服务器的参数配置
		Properties props = new Properties(); // 参数配置
		props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求)
		props.setProperty("mail.smtp.host", emailConfig.getSenderEmailSMTPHost()); // 发件人的邮箱的 SMTP 服务器地址

		// 2. 根据配置创建会话对象, 用于和邮件服务器交互
		Session session = Session.getInstance(props);
		// 设置为debug模式, 可以查看详细的发送 log
		session.setDebug(true);

		// 4. 根据 Session 获取邮件传输对象
		Transport transport = session.getTransport();
		transport.connect(emailConfig.getSenderEmailAddr(), emailConfig.getSenderEmailPwd());

		for (String receiver : emailConfig.getReceivers()) {
			// 3. 创建一封邮件
			MimeMessage message = createMimeMessage(session, emailConfig.getSenderEmailAddr(), receiver, title, content);
			// 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人,
			// 密送人
			transport.sendMessage(message, message.getAllRecipients());
		}

		// 7. 关闭连接
		transport.close();
	} catch (Exception e) {
		LoggerUtils.error("", e);
	}
}
 
源代码12 项目: redesocial   文件: Enviar_email.java
public static void main(String[] args) {
      Properties props = new Properties();
      /** Parâmetros de conexão com servidor Gmail */
      props.put("mail.smtp.host", "smtp.gmail.com");
      props.put("mail.smtp.socketFactory.port", "465");
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.port", "465");

      Session session = Session.getDefaultInstance(props,
                  new javax.mail.Authenticator() {
                       protected PasswordAuthentication getPasswordAuthentication() 
                       {
                             return new PasswordAuthentication("[email protected]", "tjm123456");
                       }
                  });
      /** Ativa Debug para sessão */
      session.setDebug(true);
      try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]")); //Remetente

            Address[] toUser = InternetAddress //Destinatário(s)
                       .parse("[email protected]");  
            message.setRecipients(Message.RecipientType.TO, toUser);
            message.setSubject("Enviando email com JavaMail");//Assunto
            message.setText("Enviei este email utilizando JavaMail com minha conta GMail!");
            /**Método para enviar a mensagem criada*/
            Transport.send(message);
            System.out.println("Feito!!!");
       } catch (MessagingException e) {
            throw new RuntimeException(e);
      }
}
 
源代码13 项目: nano-framework   文件: AbstractMailSenderFactory.java
/**
 * 以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;
}
 
源代码14 项目: jeecg   文件: MailUtil.java
/**
 * 发送电子邮件
 * 
 * @param smtpHost
 *            发信主机
 * @param receiver
 *            邮件接收者
 * @param title
 *            邮件的标题
 * @param content
 *            邮件的内容
 * @param sender
 *            邮件发送者
 * @param user
 *            发送者邮箱用户名
 * @param pwd
 *            发送者邮箱密码
 * @throws MessagingException 
 */
public static void sendEmail(String smtpHost, String receiver,
		String title, String content, String sender, String user, String pwd) throws MessagingException
		 {
	Properties props = new Properties();
	props.put("mail.host", smtpHost);
	props.put("mail.transport.protocol", "smtp");
	// props.put("mail.smtp.host",smtpHost);//发信的主机,这里要把您的域名的SMTP指向正确的邮件服务器上,这里一般不要动!
	props.put("mail.smtp.auth", "true");
	Session s = Session.getDefaultInstance(props);
	s.setDebug(true);
	MimeMessage message = new MimeMessage(s);
	// 给消息对象设置发件人/收件人/主题/发信时间
	// 发件人的邮箱
	InternetAddress from = new InternetAddress(sender);
	message.setFrom(from);
	InternetAddress to = new InternetAddress(receiver);
	message.setRecipient(Message.RecipientType.TO, to);
	message.setSubject(title);
	message.setSentDate(new Date());
	// 给消息对象设置内容
	BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
	mdp.setContent(content, "text/html;charset=gb2312");// 给BodyPart对象设置内容和格式/编码方式防止邮件出现乱码
	Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
	// 象(事实上可以存放多个)
	mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
	message.setContent(mm);// 把mm作为消息对象的内容

	message.saveChanges();
	Transport transport = s.getTransport("smtp");
	transport.connect(smtpHost, user, pwd);// 设置发邮件的网关,发信的帐户和密码,这里修改为您自己用的
	transport.sendMessage(message, message.getAllRecipients());
	transport.close();
}
 
源代码15 项目: nano-framework   文件: AbstractMailSenderFactory.java
/**
 * 以文本格式发送邮件.
 *
 * @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;
}
 
源代码16 项目: hop   文件: ScriptAddedFunctions.java
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." );
  }
}
 
源代码17 项目: pentaho-kettle   文件: ScriptAddedFunctions.java
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." );
  }
}
 
源代码18 项目: EasyHousing   文件: Tool.java
public static void sendPassword(String receiveMailAccount, String password) throws Exception {

        Properties props = new Properties();                    
        props.setProperty("mail.transport.protocol", "smtp");  

        props.setProperty("mail.smtp.host", myEmailSMTPHost);
        props.setProperty("mail.smtp.auth", "true"); 
        

        Session session = Session.getDefaultInstance(props);
        session.setDebug(true);                         
   
        MimeMessage message = createMimeMessage(session, myEmailAccount, receiveMailAccount, password);

     
        Transport transport = session.getTransport();

        transport.connect(myEmailAccount, myEmailPassword);


        transport.sendMessage(message, message.getAllRecipients());

        transport.close();
    }
 
源代码19 项目: nifi   文件: TestListenSMTP.java
@Test(expected = MessagingException.class)
public void testListenSMTPwithTooLargeMessage() throws Exception {
    final ListenSMTP processor = new ListenSMTP();
    final TestRunner runner = TestRunners.newTestRunner(processor);

    final int port = NetworkUtils.availablePort();
    runner.setProperty(ListenSMTP.SMTP_PORT, String.valueOf(port));
    runner.setProperty(ListenSMTP.SMTP_MAXIMUM_CONNECTIONS, "3");
    runner.setProperty(ListenSMTP.SMTP_MAXIMUM_MSG_SIZE, "10 B");

    runner.run(1, false);

    assertTrue(String.format("expected server listening on %s:%d", "localhost", port), NetworkUtils.isListening("localhost", port, 5000));

    final Properties config = new Properties();
    config.put("mail.smtp.host", "localhost");
    config.put("mail.smtp.port", String.valueOf(port));
    config.put("mail.smtp.connectiontimeout", "5000");
    config.put("mail.smtp.timeout", "5000");
    config.put("mail.smtp.writetimeout", "5000");

    final Session session = Session.getInstance(config);
    session.setDebug(true);

    MessagingException messagingException = null;
    try {
        final Message email = new MimeMessage(session);
        email.setFrom(new InternetAddress("[email protected]"));
        email.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
        email.setSubject("This is a test");
        email.setText("MSG-0");
        Transport.send(email);
    } catch (final MessagingException e) {
        messagingException = e;
    }

    runner.shutdown();
    runner.assertAllFlowFilesTransferred(ListenSMTP.REL_SUCCESS, 0);

    if (messagingException != null) throw messagingException;
}
 
源代码20 项目: tn5250j   文件: SendEMail.java
/**
 * 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;
}