Java 类javax.mail.Transport 实例源码

项目:AndroidKillerService    文件:SimpleMailSender.java   
public boolean sendTextMail(MailSenderInfo mailInfo) {
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }
    try {
        Message mailMessage = new MimeMessage(Session.getInstance(pro, authenticator));
        mailMessage.setFrom(new InternetAddress(mailInfo.getFromAddress()));
        mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(mailInfo.getToAddress()));
        mailMessage.setSubject(mailInfo.getSubject());
        mailMessage.setSentDate(new Date());
        mailMessage.setText(mailInfo.getContent());
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
        return false;
    }
}
项目:datarouter    文件:DatarouterEmailTool.java   
private static void sendEmail(String fromEmail, String toEmail, String subject, String body, boolean html)
throws MessagingException{
    MimeMessage message = new MimeMessage(MAILING_SESSION);
    message.setFrom(new InternetAddress(fromEmail));
    InternetAddress[] addresses = InternetAddress.parse(toEmail);//one or more addresses
    message.addRecipients(RecipientType.TO, addresses);
    message.setReplyTo(addresses);
    message.setSubject(subject);
    String subType;
    if(html){
        subType = "html";
    }else{
        subType = "plain";
    }
    message.setText(body, "UTF-8", subType);
    Transport.send(message);
}
项目:kettle_support_kettle8.0    文件:Message.java   
public static boolean iMessage() {
    try {
        message.setContent(mp);
        message.saveChanges();
        Session mailSession = Session.getInstance(props, null);
        Transport transport = mailSession.getTransport("smtp");
        transport.connect((String) props.get("mail.smtp.host"),
                (Integer) props.get("mail.smtp.port"), username, password);
        transport.sendMessage(message,
                message.getRecipients(javax.mail.Message.RecipientType.TO));
        transport.close();
    } catch (MessagingException e) {
        return false;
    }
    return true;
}
项目:HustEating    文件:Mail.java   
/**
 * 发送邮件,从公邮里发邮件给成员变量email。
 *
 * @throws Exception 可能会有异常抛出,建议打出Log。
 */
public void sendCodeMail() throws MessagingException, UnsupportedEncodingException {
    if (email == null) {
        Log.e("sendCodeMail","调用错误");
        return;
    }
    //创建一封邮件
    MimeMessage message = createCodeMessage(session, myEmailAccount, email);

    Transport transport = session.getTransport();

    //使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错
    transport.connect(myEmailAccount, myEmailPassword);
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}
项目:rapidminer    文件:MailSenderSMTP.java   
@Override
public void sendEmail(String address, String subject, String content, Map<String, String> headers) throws Exception {
    Session session = MailUtilities.makeSession();
    if (session == null) {
        // LogService.getRoot().warning("Unable to create mail session. Not sending mail to "+address+".");
        LogService.getRoot().log(Level.WARNING, "com.rapidminer.tools.MailSenderSMTP.creating_mail_session_error",
                address);
    }
    MimeMessage msg = new MimeMessage(session);
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setFrom();
    msg.setSubject(subject, "UTF-8");
    msg.setSentDate(new Date());
    msg.setText(content, "UTF-8");

    if (headers != null) {
        for (Entry<String, String> header : headers.entrySet()) {
            msg.setHeader(header.getKey(), header.getValue());
        }
    }
    Transport.send(msg);
}
项目:Mastering-Java-EE-Development-with-WildFly    文件:SendMailWithResource.java   
public void send(String addresses, String topic, String textMessage) {

        try {
            session.getProperties().put("mail.smtp.port", 25000);
            Message message = new MimeMessage(session);
            message.setRecipients(TO, InternetAddress.parse(addresses));
            message.setSubject(topic);
            message.setText(textMessage);

            Transport.send(message);
            logger.info("sent mail with resource!");

        } catch (MessagingException e) {
            logger.log(WARNING, "Cannot send mail", e);
        }
    }
项目:alfresco-greenmail    文件:GreenMailUtil.java   
public static void sendTextEmail(String to, String from, String subject, String msg, final ServerSetup setup) {
    try {
        Session session = getSession(setup);

        Address[] tos = new javax.mail.Address[0];
        tos = new InternetAddress[]{new InternetAddress(to)};
        Address[] froms = new InternetAddress[]{new InternetAddress(from)};
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setSubject(subject);
        mimeMessage.setFrom(froms[0]);

        mimeMessage.setText(msg);
        Transport.send(mimeMessage, tos);
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
}
项目:ats-framework    文件:Test_MailReportSender.java   
@Test
public void sendReport() throws MessagingException {

    mockStatic(Transport.class);

    expect(ReportConfigurator.getInstance()).andReturn(mockReportConfigurator);
    expect(mockReportConfigurator.getSmtpServerName()).andReturn("localhost");
    expect(mockReportConfigurator.getSmtpServerPort()).andReturn("25");
    expect(mockReportConfigurator.getAddressesTo()).andReturn(new String[]{ "userTo" });
    expect(mockReportConfigurator.getAddressesCc()).andReturn(new String[0]);
    expect(mockReportConfigurator.getAddressesBcc()).andReturn(new String[0]);
    expect(mockReportConfigurator.getAddressFrom()).andReturn("userFrom");

    Transport.send(isA(Message.class));

    replayAll();

    triggerRun();

    verifyAll();
}
项目:ats-framework    文件:Test_MailReportSender.java   
@Test( expected = MailReportSendException.class)
public void errorOnSend() throws MessagingException {

    mockStatic(Transport.class);

    expect(ReportConfigurator.getInstance()).andReturn(mockReportConfigurator);
    expect(mockReportConfigurator.getSmtpServerName()).andReturn("localhost");
    expect(mockReportConfigurator.getSmtpServerPort()).andReturn("25");
    expect(mockReportConfigurator.getAddressesTo()).andReturn(new String[]{ "userTo" });
    expect(mockReportConfigurator.getAddressesCc()).andReturn(new String[0]);
    expect(mockReportConfigurator.getAddressesBcc()).andReturn(new String[0]);
    expect(mockReportConfigurator.getAddressFrom()).andReturn("userFrom");

    Transport.send(isA(Message.class));
    expectLastCall().andThrow(new MessagingException());

    replayAll();

    triggerRun();

    verifyAll();
}
项目: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;
    }

}
项目:Spring-web-shop-project    文件:SendEmailDeleteAccount.java   
public static String sendCode(User user, HttpServletRequest request) {
    try {
        Session session = EmailActions.authorizeWebShopEmail();

        String code = Long.toHexString(Double.doubleToLongBits(Math.random()));
        request.getSession().setAttribute("deleteAccountCode", code);
        request.getSession().setAttribute("userName", user.getLogin());
        System.out.println(code);

        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(ApplicationProperties.SHOP_EMAIL));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(user.geteMail(), false));
        msg.setSubject("Delete account");
        msg.setText("Link : " + ApplicationProperties.URL + ApplicationProperties.PROJECT_NAME + "account/deleteAccountCode/" + code);
        msg.setSentDate(new Date());
        Transport.send(msg);

    } catch (MessagingException e) {
        System.out.println("Error : " + e);
    }
    return "loginAndRegistration/reset/codePassword";
}
项目:unitimes    文件:JavaMailWrapper.java   
@Override
public void send() throws MessagingException, UnsupportedEncodingException {
    long t0 = System.currentTimeMillis();
    try {
        if (iMail.getFrom() == null || iMail.getFrom().length == 0)
            setFrom(ApplicationProperty.EmailSenderAddress.value(), ApplicationProperty.EmailSenderName.value());
        if (iMail.getReplyTo() == null || iMail.getReplyTo().length == 0)
            setReplyTo(ApplicationProperty.EmailReplyToAddress.value(), ApplicationProperty.EmailReplyToName.value());
        iMail.setSentDate(new Date());
        iMail.setContent(iBody);
        iMail.saveChanges();
        Transport.send(iMail);
    } finally {
        long t = System.currentTimeMillis() - t0;
        if (t > 30000)
            sLog.warn("It took " + new DecimalFormat("0.00").format(t / 1000.0) + " seconds to send an email.");
        else if (t > 5000)
            sLog.info("It took " + new DecimalFormat("0.00").format(t / 1000.0) + " seconds to send an email.");
    }
}
项目:asura    文件:SendMailJob.java   
/**
 * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
 */
public void execute(JobExecutionContext context)
    throws JobExecutionException {

    JobDataMap data = context.getMergedJobDataMap();

    MailInfo mailInfo = populateMailInfo(data, createMailInfo());

    getLog().info("Sending message " + mailInfo);

    try {
        MimeMessage mimeMessage = prepareMimeMessage(mailInfo);

        Transport.send(mimeMessage);
    } catch (MessagingException e) {
        throw new JobExecutionException("Unable to send mail: " + mailInfo,
                e, false);
    }

}
项目:DiscussionPortal    文件:SendMail.java   
public String sendMail() {

    mail.setPassword(Mailer.PA);
    mail.setHost(Mailer.HOST);
    mail.setSender(Mailer.SENDER);
    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", mail.getHost());
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.socketFactory.port", "465");    
       properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");     
       properties.put("mail.smtp.port", "465");    
    Session session = Session.getInstance(properties,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAurhentication() {
                    return new PasswordAuthentication(mail.getSender(), mail.getPassword());
                }
            });

    try {

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(mail.getSender()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(mail.getEmailId()));
        message.setSubject(mail.getSubject());
        message.setText(mail.getMessage());
        Transport.send(message, mail.getSender(),mail.getPassword());
        System.out.println("Mail Sent");
        return StatusCode.SUCCESS;
    } catch(Exception ex) {
        throw new RuntimeException("Error while sending mail" + ex);
    }
}
项目:flow-platform    文件:SmtpUtil.java   
/**
 * authentication
 */
public static Boolean authentication(EmailSettingContent emailSetting) {

    Properties props = buildProperty(emailSetting);

    Session session = Session.getInstance(props, null);
    try {
        Transport transport = session.getTransport("smtp");
        String username = null;
        String password = null;
        if (emailSetting.isAuthenticated()) {
            username = emailSetting.getUsername();
            password = emailSetting.getPassword();
        }
        transport.connect(emailSetting.getSmtpUrl(), emailSetting.getSmtpPort(), username,
            password);
        transport.close();
        return true;
    } catch (Throwable throwable) {
        return false;
    }
}
项目:Cognizant-Intelligent-Test-Scripter    文件:Mailer.java   
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();
}
项目:Higher-Cloud-Computing-Project    文件:EmailUtils.java   
public static void sendAccountActivateEmail(String email, String uuid, int userId) {
  Session session;
  try {
    session = getSession();
    MimeMessage message = new MimeMessage(session);
    message.setSubject("������֤��");
    message.setSentDate(new Date());
    message.setFrom(new InternetAddress(FROM));
    message.setRecipient(RecipientType.TO, new InternetAddress(email));
    message.setContent("�����û�"+userId+":������֤��Ϊ��"+uuid,
        "text/html;charset=utf-8");
    message.saveChanges();
    Transport.send(message);
  } catch (Exception e) {
    e.printStackTrace();
  }
}
项目:web-framework-for-java    文件:MailHelper.java   
public static void sendMail(String host, int port, String username, String password, String recipients,
        String subject, String content, String from) throws AddressException, MessagingException {

    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(username, password);
        }
    });

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
    message.setSubject(subject);
    message.setText(content);

    Transport.send(message);
}
项目:HustEating    文件:Mail.java   
/**
 * 发送反馈邮件
 * @param detail
 * @throws UnsupportedEncodingException
 * @throws MessagingException
 */
public void sendFeedBackMail(String detail) throws UnsupportedEncodingException, MessagingException {
    MimeMessage message = createFeedBackMsg(session,myEmailAccount,detail);
    Transport transport = session.getTransport();
    transport.connect(myEmailAccount, myEmailPassword);
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}
项目:solo-spring    文件:EmailSender.java   
/**
 * Sends email.
 * 
 * @throws MessagingException
 *             message exception
 */
private void sendMail() throws MessagingException {

    /*
     * Properties used to construct a email sending connection protocal.
     */
    final Properties props = new Properties();

    props.put("mail.smtp.host", MAIL_HOST);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");

    final Authenticator auth = new SMTPAuthenticator();
    final MimeMessage msg = new MimeMessage(Session.getDefaultInstance(props, auth));

    msg.setFrom(new InternetAddress(from));
    msg.setRecipient(RecipientType.TO, new InternetAddress(to));
    msg.setSubject(subject);
    msg.setText(message);
    Transport.send(msg);
}
项目:AndroidKillerService    文件:SimpleMailSender.java   
public boolean sendAttachMail(MailSenderInfo mailInfo) {
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }
    try {
        Message mailMessage = new MimeMessage(Session.getInstance(pro, authenticator));
        mailMessage.setFrom(new InternetAddress(mailInfo.getFromAddress()));
        mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(mailInfo.getToAddress()));
        mailMessage.setSubject(mailInfo.getSubject());
        mailMessage.setSentDate(new Date());
        Multipart multi = new MimeMultipart();
        BodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
        multi.addBodyPart(textBodyPart);
        for (String path : mailInfo.getAttachFileNames()) {
            DataSource fds = new FileDataSource(path);
            BodyPart fileBodyPart = new MimeBodyPart();
            fileBodyPart.setDataHandler(new DataHandler(fds));
            fileBodyPart.setFileName(path.substring(path.lastIndexOf("/") + 1));
            multi.addBodyPart(fileBodyPart);
        }
        mailMessage.setContent(multi);
        mailMessage.saveChanges();
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
        return false;
    }
}
项目:Spring-web-shop-project    文件:SendEmailUserAccount.java   
public static void sendEmailWithOrder(String text, String eMail, HttpServletRequest request) {
    try {
        Session session = EmailActions.authorizeWebShopEmail();

        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(ApplicationProperties.SHOP_EMAIL));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(eMail, false));
        msg.setSubject("Shop order");
        msg.setText(text);
        msg.setSentDate(new Date());
        Transport.send(msg);
    } catch (MessagingException e) {
        System.out.println("Error : " + e);
    }
}
项目:NEILREN4J    文件:EmailUtils.java   
public void sendHtmlEmail(EmailObject email) throws Exception {
    // 创建Session实例对象
    Session session = Session.getInstance(props, new EmailAuthenticator());

    // 创建MimeMessage实例对象
    MimeMessage message = new MimeMessage(session);
    // 设置邮件主题
    message.setSubject(email.getEmailSubject(),"utf-8");
    // 设置发送人
    message.setFrom(new InternetAddress(from));
    // 设置发送时间
    message.setSentDate(new Date());
    // 设置收件人
    message.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(email.getToEmail()));
    // 设置html内容为邮件正文,指定MIME类型为text/html类型,并指定字符编码为gbk
    message.setContent(email.getEmailContent(), "text/html;charset=utf-8");
    // 保存并生成最终的邮件内容
    message.saveChanges();
    // 发送邮件
    Transport.send(message);
    //记录邮件发送日志
    SendEmailLog sendEmailLog = new SendEmailLog();
    sendEmailLog.setToemail(email.getToEmail());
    sendEmailLog.setSubject(email.getEmailSubject());
    sendEmailLog.setSenddate(new Date());
    sendEmailLog.setContent(email.getEmailContent());
    sendEmailLogDao.insert(sendEmailLog);
}
项目:PTEAssistant    文件:EamilReporter.java   
public void report(UserSetting userSetting, SearchResult searchResult, int resultState) {
    if(! (boolean)config.get("enableMailReport"))
        return;

    final Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.host", "smtp.163.com");
    props.put("mail.user", config.get("fromEmailUser"));
    props.put("mail.password", config.get("fromEmailPassword"));

    // 构建授权信息,用于进行SMTP进行身份验证
    Authenticator authenticator = new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(props.getProperty("mail.user"), props.getProperty("mail.password"));
        }
    };
    Session mailSession = Session.getInstance(props, authenticator);
    try {
    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress(props.getProperty("mail.user")));
    message.setRecipient(RecipientType.TO, new InternetAddress(config.get("toEmailUser").toString()));
    message.setSubject("PTE助手通知");

    String content = String.format("账号 %s 已搜索到可用约会: 时间=%s, 地点=%s",
            userSetting.user.username, CalendarUtils.chinese(searchResult.apptTime), searchResult.testCenter);
    if(resultState > -1) {
        content += "<br>";
        content += resultState == 1 ? "并报名成功" : "但报名失败";
    }
    message.setContent(content, "text/html;charset=UTF-8");

    Transport.send(message);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}
项目:iBase4J-Common    文件:EmailSender.java   
/**
 * 发送邮件
 */
public boolean sendout() {
    try {
        mimeMsg.setContent(mp);
        mimeMsg.saveChanges();

        logger.info(Resources.getMessage("EMAIL.SENDING"));
        Session mailSession = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                if (userkey == null || "".equals(userkey.trim())) {
                    return null;
                }
                return new PasswordAuthentication(username, userkey);
            }
        });
        Transport transport = mailSession.getTransport("smtp");
        transport.connect((String) props.get("mail.smtp.host"), username, password);
        // 设置发送日期
        mimeMsg.setSentDate(new Date());
        // 发送
        transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
        if (mimeMsg.getRecipients(Message.RecipientType.CC) != null) {
            transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.CC));
        }
        logger.info(Resources.getMessage("EMAIL.SEND_SUCC"));
        transport.close();
        return true;
    } catch (Exception e) {
        logger.error(Resources.getMessage("EMAIL.SEND_ERR"), e);
        return false;
    }
}
项目:webpage-update-subscribe    文件:EmailServer.java   
/**
 * 發送單條email
 * 
 * @param emailInfo
 */
public void send(final EmailInfo emailInfo) {
    this.theadPool.execute(new Runnable() {
        public void run() {
            EmailContext emailContext = new EmailContext();
            emailContext.setEmailInfo(emailInfo);
            try {
                Message msg = buildEmailMessage(emailInfo);
                Transport.send(msg);
            } catch (Exception e) {
                emailContext.setThrowable(e);
            }
        }
    });
}
项目:alfresco-repository    文件:AlfrescoJavaMailSender.java   
/**
 * Create a new {@link Transport} using the {@link Session} returned by {@link JavaMailSenderImpl#getSession() getSession()}.
 * 
 * @param key A {@link URLName} containing the connection details
 * @return A new {@link Transport}
 */
@Override
public Object makeObject(Object key) throws Exception
{
    if ((key instanceof URLName) == false)
    {
        throw new IllegalArgumentException("Invlid key type");
    }
    log.debug("Creating new Transport");
    URLName urlName = (URLName) key;
    Transport transport = getSession().getTransport(urlName.getProtocol()); 
    transport.connect(urlName.getHost(), urlName.getPort(), urlName.getUsername(), urlName.getPassword());
    return transport;
}
项目:alfresco-repository    文件:AlfrescoJavaMailSender.java   
/**
 * Disconnects the pooled {@link Transport} object.
 * 
 * @param key {@link URLName} containing the connection details.
 * @param object Pooled {@link Transport}
 */
@Override
public void destroyObject(Object key, Object object) throws Exception
{
    if (object instanceof Transport == false)
    {
        throw new IllegalArgumentException("Unexpected object type");
    }
    log.debug("Destroying Transpaort");
    Transport transport = (Transport)object;
    transport.close();
}
项目:alfresco-repository    文件:AlfrescoJavaMailSender.java   
/**
 * Checks to see if the pooled {@link Transport} is still connected.
 * 
 * @param key {@link URLName} containing the connection details.
 * @param object Pooled {@link Transport}
 * 
 * @return true if the pooled transport is still connected, or false,  otherwise.
 */
@Override
public boolean validateObject(Object key, Object object)
{
    if (object instanceof Transport == false)
    {
        throw new IllegalArgumentException("Unexpected object type");
    }
    log.debug("Validating transport");
    Transport transport = (Transport)object;
    return transport.isConnected();
}
项目:alfresco-repository    文件:AlfrescoJavaMailSender.java   
/**
 * @return A new {@code PooledTransportWrapper} which borrows a pooled {@link Transport} on connect, and returns it to
 *             the pool on close.  
 */
@Override
protected Transport getTransport(Session session) throws NoSuchProviderException
{
    return new PooledTransportWrapper(transportPool, session, getProtocol());

}
项目:YiDu-Novel    文件:MailUtils.java   
/**
 * 发邮件处理
 * 
 * @param toAddr
 *            邮件地址
 * @param content
 *            邮件内容
 * @return 成功标识
 */
public static boolean sendMail(String toAddr, String title, String content, boolean isHtmlFormat) {

    final String username = YiDuConstants.yiduConf.getString(YiDuConfig.MAIL_SMTP_USERNAME);
    final String password = YiDuConstants.yiduConf.getString(YiDuConfig.MAIL_SMTP_PASSWORD);

    Properties props = new Properties();
    props.put("mail.smtp.auth", YiDuConstants.yiduConf.getBoolean(YiDuConfig.MAIL_SMTP_AUTH, true));
    props.put("mail.smtp.starttls.enable",
            YiDuConstants.yiduConf.getBoolean(YiDuConfig.MAIL_SMTP_STARTTLS_ENABLE, true));
    props.put("mail.smtp.host", YiDuConstants.yiduConf.getString(YiDuConfig.MAIL_SMTP_HOST));
    props.put("mail.smtp.port", YiDuConstants.yiduConf.getInt(YiDuConfig.MAIL_SMTP_PORT, 25));

    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(YiDuConstants.yiduConf.getString(YiDuConfig.MAIL_SMTP_FROM)));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddr));
        message.setSubject(title);
        if (isHtmlFormat) {
            message.setContent(content, "text/html");
        } else {
            message.setText(content);
        }
        Transport.send(message);

    } catch (MessagingException e) {
        logger.warn(e);
        return false;
    }
    return true;

}
项目:automat    文件:EmailSender.java   
/**
 * 发送邮件
 * 
 * @param name String
 * @param pass String
 */
public boolean sendout() {
    try {
        mimeMsg.setContent(mp);
        mimeMsg.saveChanges();

        logger.info(Resources.getMessage("EMAIL.SENDING"));
        Session mailSession = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                if (userkey == null || "".equals(userkey.trim())) {
                    return null;
                }
                return new PasswordAuthentication(username, userkey);
            }
        });
        Transport transport = mailSession.getTransport("smtp");
        transport.connect((String) props.get("mail.smtp.host"), username, password);
        // 设置发送日期
        mimeMsg.setSentDate(new Date());
        // 发送
        transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
        if (mimeMsg.getRecipients(Message.RecipientType.CC) != null) {
            transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.CC));
        }
        logger.info(Resources.getMessage("EMAIL.SEND_SUCC"));
        transport.close();
        return true;
    } catch (Exception e) {
        logger.error(Resources.getMessage("EMAIL.SEND_ERR"), e);
        return false;
    }
}
项目:DDNS_Server    文件:ForgotServlet.java   
public void sendMail(int uID, String URLlink, String Uname, String mailuser, String mailpass, String mailserver, String mailport, String mailsendadd, DB dbProperties) {

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", mailserver);
    props.put("mail.smtp.port", mailport);

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

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(mailsendadd));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(ForgotDao.getEmail(uID, dbProperties)));
        message.setSubject("Forgot your password!");
        message.setContent("Dear "+Uname+", <BR><BR> Please click the following link to gain access to your account. <BR><BR> <a href=\""+URLlink+"\">Activate Account</a> <BR><BR> Thank You,", "text/html; charset=utf-8");

        Transport.send(message);

        System.out.println("Forgot Password E-mail Sent - "+ForgotDao.getEmail(uID, dbProperties));

    } catch (MessagingException e) {

        System.out.println("Error - Forgot Password E-mail Send FAILED - "+ForgotDao.getEmail(uID, dbProperties));
        throw new RuntimeException(e);
    }   
}
项目:java-gps-tracking-server    文件:MessageSenderConsumer.java   
private void sendEmail(Message msg, MimeMessage message) {
    try {
        switch (msg.getMessageType()) {
            case CRITICAL_SERVER_FAILURE: {
                message.setSubject("ADA | CRITICAL SERVER FAILURE");
                message.setText(msg.getMessage() + " > " + msg.getPayload().toString());
                break;
            }
            case MSG_EXCEPTION: {
                message.setSubject("ADA | SERVER EXCEPTION");
                message.setText(msg.getMessage() + " > " + msg.getPayload().toString());
                break;
            }
            case DEVICE_DOWN: {
                message.setSubject("ADA | DEAD DEVICES");
                message.setText(msg.getMessage() + " > " + msg.getPayload().toString());
                break;
            }
            case SERVER_STARTUP: {
                message.setSubject("ADA | SERVER RESTARTING");
                List<String> s = (List<String>) msg.getPayload();
                String ms = "";
                for (int i = 0; i < s.size(); i++) {
                    ms += " { " + s.get(i) + " } ";
                }
                message.setText(ms);
                break;
            }
            default:
                break;
        }
        Transport.send(message);
    } catch (MessagingException e) {
        REG_LOGGER.fatal("MailingError", e);
    }
}
项目:Hotel-Properties-Management-System    文件:SendEmailToUser.java   
public void sendTheEmail() {
    try {
        Transport.send(message);

    } catch (MessagingException e) {
        loggingEngine.setMessage("Cannot send email! : " + e.getMessage());
    }
}
项目: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);
    }
}
项目:spr    文件:SendMail.java   
public static void sendEmail(String host, String port,
        final String userName, final String password, String toAddress,
        String subject, String message, String nombreArchivoAdj, String urlArchivoAdj)
                throws AddressException, MessagingException {

    // sets SMTP server properties
    Properties properties = new Properties();
    properties.put("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");

    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    };

    Session session = Session.getInstance(properties, auth);

    //Se crea la parte del cuerpo del mensaje.
    BodyPart texto = new MimeBodyPart();
    texto.setText(message);        
    BodyPart adjunto = new MimeBodyPart();

    if(nombreArchivoAdj != null ){          
     adjunto.setDataHandler(new DataHandler(new FileDataSource(urlArchivoAdj)));
     adjunto.setFileName(nombreArchivoAdj);
    }

    //Juntar las dos partes
    MimeMultipart multiParte = new MimeMultipart();
    multiParte.addBodyPart(texto);
    if (nombreArchivoAdj != null) multiParte.addBodyPart(adjunto);

    // creates a new e-mail message
    Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(userName));
    InternetAddress[] toAddresses = null;
    toAddresses = InternetAddress.parse(toAddress, false);

    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    msg.setSubject(subject);
    msg.setSentDate(new Date());
    //msg.setText(message);
    msg.setContent(multiParte);

    // sends the e-mail
    Transport.send(msg);       

}
项目:Blockchain-Academic-Verification-Service    文件:EmailService.java   
@Override
public boolean sendTokenMail(final String[] to, final String contractAddress, final String artifactId,
                             final String registryContract) {
    setupProperties();
    Session session = Session.getDefaultInstance(properties);
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(new InternetAddress(username));
        InternetAddress[] toAddress = new InternetAddress[to.length];

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

        for (int i = 0; i < toAddress.length; i++) {
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);
        }
        message.setSubject(TOKEN_SUBJECT);
        message.setText(tokenBody + contractAddress + "\nArtifact ID: " + artifactId
                + "\n\nBelow is the Unilog Registry. Add this into the verifiers portal if you need to"
                + " verify a token: \n" + registryContract);
        Transport transport = session.getTransport("smtp");
        transport.connect(host, username, password);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        LOGGER.info("Token email has been sent");
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}