Java 类javax.mail.Authenticator 实例源码

项目:webpage-update-subscribe    文件:EmailServer.java   
/**
 * 郵件監聽器
 */
//private List<EmailSendListener> emailSendListeners = new ArrayList<EmailSendListener>();

public void init() {
    final Properties properties = SysConfig.getProperties();
    this.theadPool = Executors.newFixedThreadPool(POOL_SIZE);
    this.session = Session.getDefaultInstance(properties,
            new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(properties
                            .getProperty("mail.smtp.username"), properties
                            .getProperty("mail.smtp.password"));
                }
            });
    username = properties.getProperty("mail.smtp.username");
    //设置调试模式(输出调试信息)
    this.session.setDebug(false);
}
项目: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;
    }

}
项目:UtilsMaven    文件:MailUtils.java   
/**
 * 获取用户与邮件服务器的连接
 *
 * @param host     邮件主机名
 * @param username 发件人的用户名
 * @param password 发件人的用户名密码
 * @return 返回指定用户与指定邮件服务器绑定的一个连接(会话)
 */
public static Session getSession(String host, final String username,
                                 final String password) {
    // 设置配置文件,邮件主机和是否认证
    Properties property = new Properties();
    property.put("mail.host", host);
    property.put("mail.smtp.auth", "true");
    // 设置用户名和密码
    Authenticator auth = new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            // TODO Auto-generated method stub
            return new PasswordAuthentication(username, password);
        }
    };
    // 获取与邮件主机的连接
    Session session = Session.getInstance(property, auth);
    return session;
}
项目:bdf2    文件:EmailSender.java   
private Session getMailSession(){
    if(session==null){
        Properties properties = new Properties();
        properties.put("mail.smtp.host",smtpHost);
        if(StringUtils.isNotEmpty(smtpPort)){
            properties.put("mail.smtp.port",Integer.parseInt(smtpPort));
        }
        if(smtpIsAuth) {
            properties.put("mail.smtp.auth","true");
            session = Session.getDefaultInstance(properties,
                    new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(smtpUser,smtpPassword);
                }
            });
        } else {
            session = Session.getDefaultInstance(properties);
        }
    }
    return session;
}
项目:bdf2    文件:EmailSender.java   
private Session getMailSession(){
    if(session==null){
        Properties properties = new Properties();
        properties.put("mail.smtp.host",smtpHost);
        if(StringUtils.isNotEmpty(smtpPort)){
            properties.put("mail.smtp.port",Integer.parseInt(smtpPort));
        }
        if(smtpIsAuth) {
            properties.put("mail.smtp.auth","true");
            session = Session.getDefaultInstance(properties,
                    new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(smtpUser,smtpPassword);
                }
            });
        } else {
            session = Session.getDefaultInstance(properties);
        }
    }
    return session;
}
项目:Spring-web-shop-project    文件:EmailActions.java   
public static Session authorizeWebShopEmail() throws MessagingException {
    Session session = null;
    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", "smtp.gmail.com");
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.port", "465");
    props.setProperty("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.auth", "true");
    props.put("mail.debug", "true");
    props.put("mail.store.protocol", "pop3");
    props.put("mail.transport.protocol", "smtp");
    final String username = ApplicationProperties.SHOP_EMAIL;
    final String password = ApplicationProperties.SHOP_EMAIL_PASSWORD;
    session = Session.getDefaultInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    return session;
}
项目:simbest-cores    文件:EmailUtils.java   
/**
 * 发送邮件 (暂时只支持163邮箱发送)
 * @param fromEmail 发送邮箱
 * @param toEmail 接收邮箱
 * @param emailName 163邮箱登录名
 * @param emailPassword 密码
 * @param title 发送主题
 * @param centent 发送内容
 * @throws Exception
 */
public void sendMail(String fromEmail,String toEmail,String emailName,String emailPassword,String title, String centent) throws Exception {

    Properties properties = new Properties();// 创建Properties对象
    properties.setProperty("mail.transport.protocol", appConfig.getValue("mail.transport.protocol"));// 设置传输协议
    properties.put("mail.smtp.host", appConfig.getValue("mail.SMTPHost"));// 设置发信邮箱的smtp地址
    properties.setProperty("mail.smtp.auth", "true"); // 验证
    Authenticator auth = new AjavaAuthenticator(emailName,
            emailPassword); // 使用验证,创建一个Authenticator
    Session session = Session.getDefaultInstance(properties, auth);// 根据Properties,Authenticator创建Session
    Message message = new MimeMessage(session);// Message存储发送的电子邮件信息
    message.setFrom(new InternetAddress(fromEmail));
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(
            toEmail));// 设置收信邮箱
    // 指定邮箱内容及ContentType和编码方式
    message.setContent(centent, "text/html;charset=utf-8");
    message.setSubject(title);// 设置主题
    message.setSentDate(new Date());// 设置发信时间
    Transport.send(message);// 发送

}
项目:hermes    文件:MailConnector.java   
/**
 * Creates a mail session from the underlying mail properties.
 * 
 * @return the mail session.
 */
public Session createSession() 
{
    Session session;
    if (username == null) 
    {
        session = Session.getInstance(properties);
    }
    else 
    {
        Authenticator auth = new Authenticator() 
        {
            public PasswordAuthentication getPasswordAuthentication() 
            {
                return new PasswordAuthentication(username,
                        password == null ? "" : password);
            }
        };
        session = Session.getInstance(properties, auth);
    }
    return session;
}
项目:product-ei    文件:MailToTransportUtil.java   
/**
 * Getting the connection to email using Mail API
 *
 * @return - Email message Store
 * @throws ESBMailTransportIntegrationTestException - Is thrown if an error while connecting to email store
 */
private static Store getConnection() throws ESBMailTransportIntegrationTestException {
    Properties properties;
    Session session;

    properties = new Properties();
    properties.setProperty("mail.host", "imap.gmail.com");
    properties.setProperty("mail.port", "995");
    properties.setProperty("mail.transport.protocol", "imaps");

    session = Session.getInstance(properties, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(receiver + "@" + domain,
                                              String.valueOf(receiverPassword));
        }
    });
    try {
        Store store = session.getStore("imaps");
        store.connect();
        return store;
    } catch (MessagingException e) {
        log.error("Error when creating the email store ", e);
        throw new ESBMailTransportIntegrationTestException("Error when creating the email store ", e);
    }
}
项目:SpringBBS    文件:EmailUtils.java   
public static Session getSession() {  
    Properties props = new Properties();  
    props.setProperty("mail.transport.protocol", "smtp");  
    props.setProperty("mail.smtp.host", "smtp.163.com");  
    props.setProperty("mail.smtp.port", "25");  
    props.setProperty("mail.smtp.auth", "true");  
    Session session = Session.getInstance(props, new Authenticator() {  
        @Override  
        protected PasswordAuthentication getPasswordAuthentication() {  
            String password = null;  
            InputStream is = EmailUtils.class.getResourceAsStream("password.dat");  
            byte[] b = new byte[1024];  
            try {  
                int len = is.read(b);  
                password = new String(b,0,len);  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            return new PasswordAuthentication(FROM, password);  
        }  

    });  
    return session;  
}
项目:dchatsdk    文件:AdminEmailSender.java   
private void sendEmail(JSONObject msg, String type){
    try{
        Properties props = new Properties();
        Authenticator auth = new EmailAutherticator(senderUsername,senderPassword);
        props.put("mail.smtp.host", mailHost);
        props.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(props, auth);
        MimeMessage message = new MimeMessage(session);
        Address address = new InternetAddress(senderUsername);
        message.setFrom(address);
        message.setSubject("dChat SDK Server [ "+type+" ] Mail");
        message.setText(msg.toString(), "UTF-8");
        message.setHeader("dChat SDK Server", type);
        message.setSentDate(new Date());
        message.addRecipients(Message.RecipientType.TO, new Address[]{address});
        Transport.send(message);
    }catch(Exception e){
        LOG.error("send notifier email failed! "+e.getMessage(), e);
    }
    LOG.info("Send Exception/Error Notifier Email to Admin Success!");
}
项目:yechblog    文件:SendMailUtil.java   
/**
 * ��ȡ���ڷ����ʼ���Session
 * @return
 */
public static Session getSession() {
    Properties props = new Properties();
    props.put("mail.smtp.host", HOST);//���÷�������ַ
       props.put("mail.store.protocol" , PROTOCOL);//������
       props.put("mail.smtp.port", PORT);//���ö˿�
       props.put("mail.smtp.auth" , true);

       Authenticator authenticator = new Authenticator() {
        @Override
           protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(SENDER, SENDERPWD);
           }
    };
       Session session = Session.getDefaultInstance(props,authenticator);
       return session;
}
项目:gangehi    文件:EmailService.java   
private Session getMailSession() {
    Properties properties = new Properties();

    properties.put("mail.smtp.auth", propertyService.getString("mail.smtp.auth"));
    properties.put("mail.smtp.starttls.enable", propertyService.getString("mail.smtp.starttls.enable"));
    properties.put("mail.smtp.host", propertyService.getString("mail.smtp.host"));
    properties.put("mail.smtp.port", propertyService.getString("mail.smtp.port"));

    Session session = Session.getInstance(properties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(propertyService.getString("mail.userName"), propertyService.getString("mail.password"));
        }
    });
    return session;
}
项目:jeecms6    文件:EmailSendTool.java   
/**
 * 此段代码用来发送普通电子邮件
 * 
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 * @throws UnsupportedEncodingException
 */
public void send() throws MessagingException, UnsupportedEncodingException {
    Properties props = new Properties();
    Authenticator auth = new Email_Autherticator(); // 进行邮件服务器用户认证
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.auth", "true");
    Session session = Session.getDefaultInstance(props, auth);
    // 设置session,和邮件服务器进行通讯。
    MimeMessage message = new MimeMessage(session);
    // message.setContent("foobar, "application/x-foobar"); // 设置邮件格式
    message.setSubject(mail_subject); // 设置邮件主题
    message.setText(mail_body); // 设置邮件正文
    message.setHeader(mail_head_name, mail_head_value); // 设置邮件标题

    message.setSentDate(new Date()); // 设置邮件发送日期
    Address address = new InternetAddress(mail_from, personalName);
    message.setFrom(address); // 设置邮件发送者的地址
    Address toAddress = new InternetAddress(mail_to); // 设置邮件接收方的地址
    message.addRecipient(Message.RecipientType.TO, toAddress);
    Transport.send(message); // 发送邮件
}
项目:ogham    文件:UsernamePasswordAuthenticatorBuilder.java   
@Override
public Authenticator build() {
    PropertyResolver propertyResolver = parent.environment().build();
    if (updatable) {
        if (!usernames.isEmpty() && !passwords.isEmpty()) {
            return new UpdatableUsernamePasswordAuthenticator(propertyResolver, usernames, passwords);
        }
        return null;
    }
    String username = BuilderUtils.evaluate(this.usernames, propertyResolver, String.class);
    String password = BuilderUtils.evaluate(this.passwords, propertyResolver, String.class);
    if (username != null && password != null) {
        return new UsernamePasswordAuthenticator(username, password);
    }
    return null;
}
项目:fax4j    文件:MailConnectionFactoryImpl.java   
/**
 * Creates and returns the resource.
 *  
 * @return  The resource
 */
@Override
protected MailResourcesHolder createResourceImpl()
{
    //create authenticator
    Authenticator authenticator=null;
    if(this.password!=null)
    {
        authenticator=new MailAuthenticator(this.userName,this.password);
    }

    //create session
    Session session=Session.getInstance(this.mailConnectionProperties,authenticator);

    //create transport
    Transport transport=this.createTransport(session);

    //create holder
    MailResourcesHolder resource=new MailResourcesHolder(session,transport);

    return resource;
}
项目:Lucee4    文件:SMTPConnectionPool.java   
public static SessionAndTransport getSessionAndTransport(Properties props, String key, Authenticator auth,long lifeTimespan, long idleTimespan) throws MessagingException{

   // Session
    SessionAndTransport sat=null;
    Stack<SessionAndTransport> satStack = getSATStack(key);
    sat=pop(satStack);

    // when sat still valid return it
    if(sat!=null)   {
        if(isValid(sat,lifeTimespan,idleTimespan)
            ) {
            return sat.touch();
        }
        disconnect(sat.transport);
    }

    return new SessionAndTransport(key, props, auth, lifeTimespan,idleTimespan);
}
项目:Mailer    文件:Application.java   
/**
 * Initialize the Mail Authenticator for entire application
 * 
 * @throws Exception
 */
private void initMailAuthenticator() throws Exception {
    if(appConfig == null){
        initAppConfig();
    }
    final String userId = Application.getInstance().getAppConfig()
    .getSmtpUserId();
    final String passwd = Application.getInstance().getAppConfig()
    .getSmtpPasswd();

    auth = new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userId, passwd);
        }
    };
}
项目:Mailer    文件:MailRunner.java   
@Override
protected void acquireResources() throws Exception {

    Properties smtpProps = Application.getInstance().getSMPTproperty();
    Authenticator auth = Application.getInstance().getMailAuthenticator();
    session = Session.getInstance(smtpProps, auth);

    // connect to the the server only once.
    try {
        transport = session.getTransport("smtp");
        transport.connect();
    } catch (Exception e) {
        System.out.println("[Error] Unable to connect SMTP server " + e);
        throw e;
    }

}
项目:Lucee    文件:SMTPConnectionPool.java   
public static SessionAndTransport getSessionAndTransport(Properties props, String key, Authenticator auth, long lifeTimespan, long idleTimespan) throws MessagingException{

   // Session
    SessionAndTransport sat=null;
    Stack<SessionAndTransport> satStack = getSATStack(key);
    sat=pop(satStack);

    // when sat still valid return it
    if(sat!=null)   {
         if(isValid(sat,lifeTimespan,idleTimespan)) {
            return sat.touch();
        }
        disconnect(sat.transport);
    }

    return new SessionAndTransport(key, props, auth,lifeTimespan,idleTimespan);
}
项目:imcms    文件:SMTP.java   
private void setEncryption(Email mail) {
    final String encryptionProtocol = getServerProperty("encryption.protocol");
    final String accountMail = getServerProperty("mail.address");
    final String accountMailPassword = getServerProperty("mail.password");

    if ((encryptionProtocol != null) && (accountMail != null) && (accountMailPassword != null)) {
        if (encryptionProtocol.toLowerCase().equals("tls")) {
            mail.setStartTLSEnabled(true);

        } else if (encryptionProtocol.toLowerCase().equals("ssl")) {
            mail.setSSLOnConnect(true);

        } else {
            return;
        }

        mail.setAuthenticator(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(accountMail, accountMailPassword);
            }
        });
    }
}
项目:rakam    文件:EmailClientConfig.java   
public MailSender getMailSender() {
    if (getHost() == null || getUser() == null) {
        throw new RakamException("mail.smtp.host or mail.smtp.username is not set.", NOT_IMPLEMENTED);
    }
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", isUseTls());
    props.put("mail.smtp.host", getHost());
    if (getPort() != null) {
        props.put("mail.smtp.port", getPort());
    }
    Session session = Session.getInstance(props,
            new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(getUser(), getPassword());
                }
            });
    return new MailSender(session, getFromAddress(), getFromName());
}
项目:cs-actions    文件:GetMailMessage.java   
protected Store createMessageStore() throws Exception {
    Properties props = new Properties();
    if (timeout > 0) {
        props.put("mail." + protocol + ".timeout", timeout);
    }
    Authenticator auth = new SimpleAuthenticator(username, password);
    Store store;
    if (enableTLS || enableSSL) {
        addSSLSettings(trustAllRoots, keystore, keystorePassword, trustKeystoreFile, trustPassword);
    }
    if (enableTLS) {
        store = tryTLSOtherwiseTrySSL(props, auth);
    } else if (enableSSL) {
        store = connectUsingSSL(props, auth);
    } else {
        store = configureStoreWithoutSSL(props, auth);
        store.connect();
    }
    return store;
}
项目:cs-actions    文件:GetMailMessageTest.java   
@Test
public void testConfigureStoreWithTLS() throws Exception {
    doReturn(objectMock).when(propertiesMock).setProperty("mail." + POP3_PROTOCOL + ".ssl.enable", STR_FALSE);
    doReturn(objectMock).when(propertiesMock).setProperty("mail." + POP3_PROTOCOL + ".starttls.enable", STR_TRUE);
    doReturn(objectMock).when(propertiesMock).setProperty("mail." + POP3_PROTOCOL + ".starttls.required", STR_TRUE);

    PowerMockito.whenNew(URLName.class)
            .withArguments(anyString(), anyString(), anyInt(), anyString(), anyString(), anyString())
            .thenReturn(urlNameMock);
    PowerMockito.mockStatic(Session.class);
    PowerMockito.doReturn(sessionMock)
            .when(Session.class, "getInstance", Matchers.<Properties>any(), Matchers.<Authenticator>any());
    doReturn(storeMock).when(sessionMock).getStore(any(String.class));

    addRequiredInputs();
    getMailMessageSpy.processInputs(inputs);

    Store store = getMailMessageSpy.configureStoreWithTLS(propertiesMock, authenticatorMock);
    assertEquals(storeMock, store);
    verify(propertiesMock).setProperty("mail." + POP3_PROTOCOL + ".ssl.enable", STR_FALSE);
    verify(propertiesMock).setProperty("mail." + POP3_PROTOCOL + ".starttls.enable", STR_TRUE);
    verify(propertiesMock).setProperty("mail." + POP3_PROTOCOL + ".starttls.required", STR_TRUE);
    PowerMockito.verifyStatic();
    Session.getInstance(Matchers.<Properties>any(), Matchers.<Authenticator>any());
    verify(sessionMock).getStore(POP3_PROTOCOL + SECURE_SUFFIX_FOR_POP3_AND_IMAP);
}
项目:cs-actions    文件:GetMailMessageTest.java   
/**
 * Test configureStoreWithoutSSL method.
 *
 * @throws Exception
 */
@Test
public void testConfigureStoreWithoutSSL() throws Exception {
    doReturn(objectMock).when(propertiesMock).put("mail." + POP3_PROTOCOL + ".host", HOST);
    doReturn(objectMock).when(propertiesMock).put("mail." + POP3_PROTOCOL + ".port", POP3_PORT);
    PowerMockito.mockStatic(Session.class);
    PowerMockito.doReturn(sessionMock)
            .when(Session.class, "getInstance", Matchers.<Properties>any(), Matchers.<Authenticator>any());
    doReturn(storeMock).when(sessionMock).getStore(POP3_PROTOCOL);

    addRequiredInputs();
    getMailMessageSpy.processInputs(inputs);

    Store store = getMailMessageSpy.configureStoreWithoutSSL(propertiesMock, authenticatorMock);
    assertEquals(storeMock, store);
    verify(propertiesMock).put("mail." + POP3_PROTOCOL + ".host", HOST);
    verify(propertiesMock).put("mail." + POP3_PROTOCOL + ".port", POP3_PORT);
    PowerMockito.verifyStatic();
    Session.getInstance(Matchers.<Properties>any(), Matchers.<Authenticator>any());
    verify(sessionMock).getStore(POP3_PROTOCOL);
}
项目:gocd    文件:Pop3MailClient.java   
private Folder getInboxFolder
        () throws MessagingException {
    Properties pop3Props = new Properties();
    pop3Props.setProperty("mail.pop3.host", host);
    Authenticator auth = new PopupAuthenticator();
    Session session =
            Session.getInstance(pop3Props, auth);
    URLName url = new URLName("pop3", host, port, "", username, password);
    Store store = session.getStore(url);
    store.connect();
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);
    return folder;
}
项目:dailyBot    文件:EmailConnection.java   
private static Session loadSession()
{
    Properties properties = new Properties();
    properties.put("mail.transport.protocol", "smtp");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.host", SMTP_HOST_NAME);
    properties.put("mail.smtp.auth", "true");
    Session session = Session.getDefaultInstance(properties, new Authenticator()
    {
        @Override
        public PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(username, DailyProperties
                .getProperty("dailyBot.control.connection.EmailConnection.emailFromPassword"));
        }
    });
    return session;
}
项目:bees-shop-clickstart    文件:MailSessionFactoryBean.java   
@Override
public void afterPropertiesSet() throws Exception {
    if (Strings.isNullOrEmpty(this.smtpUser)) {
        logger.info("Initialize anonymous mail session");
        mailSession = Session.getInstance(smtpProperties);
    } else {
        logger.info("Initialize mail session with user='{}', password='xxx'", smtpUser);

        smtpProperties.setProperty("mail.smtp.auth", "true");
        mailSession = Session.getInstance(smtpProperties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUser, smtpPassword);
            }
        });
    }
    mailSession.setDebug(debug);
}
项目:growslowly    文件:DocomoProvider.java   
@Override
public Session getSession(final String address, final String userName, final String password) {
    Properties props = new Properties();
    try {
        props.load(new InputStreamReader(getClass().getResourceAsStream("/docomo.properties")));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    props.setProperty("mail.from", address);
    props.setProperty("mail.smtp.user", userName);
    props.setProperty("mail.smtp.password", password);
    props.setProperty("mail.imap.user", userName);
    props.setProperty("mail.imap.password", password);

    return Session.getInstance(props, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    });
}
项目:growslowly    文件:GmailProvider.java   
@Override
public Session getSession(final String address, final String userName, final String password) {
    Properties props = new Properties();
    try {
        props.load(new InputStreamReader(getClass().getResourceAsStream("/gmail.properties")));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    props.setProperty("mail.from", address);
    props.setProperty("mail.smtp.user", userName);
    props.setProperty("mail.smtp.password", password);
    props.setProperty("mail.pop3s.user", userName);
    props.setProperty("mail.pop3s.password", password);
    props.setProperty("mail.imaps.user", userName);
    props.setProperty("mail.imaps.password", password);

    return Session.getInstance(props, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    });
}
项目:growslowly    文件:OCNProvider.java   
@Override
    public Session getSession(final String address, final String userName, final String password) {
//      String domain = address.substring(address.indexOf("@") + 1);
        Properties props = new Properties();
        try {
            props.load(new InputStreamReader(getClass().getResourceAsStream("/ocn.properties")));
            props.setProperty("mail.from", address);
//          props.setProperty("mail.smtp.host", "smtp.vc" + domain);
//          props.setProperty("mail.pop3.host", domain);
        } catch (IOException e) {
            return null;
        }
        return Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        });
    }
项目:growslowly    文件:ICloudProvider.java   
@Override
public Session getSession(final String address, final String userName, final String password) {
    Properties props = new Properties();
    try {
        props.load(new InputStreamReader(getClass().getResourceAsStream("/icloud.properties")));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    props.setProperty("mail.from", address);
    props.setProperty("mail.smtp.user", userName);
    props.setProperty("mail.smtp.password", password);
    props.setProperty("mail.imap.user", userName);
    props.setProperty("mail.imap.password", password);

    return Session.getInstance(props, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    });
}
项目:growslowly    文件:OutlookProvider.java   
@Override
public Session getSession(final String address, final String userName, final String password) {
    Properties props = new Properties();
    try {
        props.load(new InputStreamReader(getClass().getResourceAsStream("/outlook.properties")));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    props.setProperty("mail.from", address);
    props.setProperty("mail.smtp.user", userName);
    props.setProperty("mail.smtp.password", password);
    props.setProperty("mail.imap.user", userName);
    props.setProperty("mail.imap.password", password);

    return Session.getInstance(props, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    });
}
项目:Lottery    文件:EmailSendTool.java   
/**
 * 此段代码用来发送普通电子邮件
 * 
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 * @throws UnsupportedEncodingException
 */
public void send() throws MessagingException, UnsupportedEncodingException {
    Properties props = new Properties();
    Authenticator auth = new Email_Autherticator(); // 进行邮件服务器用户认证
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.auth", "true");
    Session session = Session.getDefaultInstance(props, auth);
    // 设置session,和邮件服务器进行通讯。
    MimeMessage message = new MimeMessage(session);
    // message.setContent("foobar, "application/x-foobar"); // 设置邮件格式
    message.setSubject(mail_subject); // 设置邮件主题
    message.setText(mail_body); // 设置邮件正文
    message.setHeader(mail_head_name, mail_head_value); // 设置邮件标题

    message.setSentDate(new Date()); // 设置邮件发送日期
    Address address = new InternetAddress(mail_from, personalName);
    message.setFrom(address); // 设置邮件发送者的地址
    Address toAddress = new InternetAddress(mail_to); // 设置邮件接收方的地址
    message.addRecipient(Message.RecipientType.TO, toAddress);
    Transport.send(message); // 发送邮件
}
项目:perfload-perfalyzer    文件:EmailReporter.java   
@Inject
public EmailReporter(final TestMetadata testMetadata, @ReportPreparationDir final File soureDir, final ResourceBundle resourceBundle,
        final Locale locale, @Nullable @ReportsBaseUrl final String reportsBaseUrl, @RelativeDestDir final File destDir,
        @EmailFrom final String fromAddress, @EmailTo final List<String> toAddresses, @SmtpProps final Properties smtpProps,
        @SubjectProps final Properties subjectProps, @Nullable final Authenticator authenticator,
        @MaxEmailHistoryItems final int maxHistoryItems, final Map<String, List<Pattern>> reportContentsConfigMap) {
    this.testMetadata = testMetadata;
    this.soureDir = soureDir;
    this.resourceBundle = resourceBundle;
    this.locale = locale;
    this.reportsBaseUrl = reportsBaseUrl;
    this.destDir = destDir;
    this.fromAddress = fromAddress;
    this.toAddresses = toAddresses;
    this.smtpProps = smtpProps;
    this.subjectProps = subjectProps;
    this.authenticator = authenticator;
    this.maxHistoryItems = maxHistoryItems;
    this.reportContentsConfigMap = reportContentsConfigMap;
}
项目:enviroCar-server    文件:AbstractSendMail.java   
@Override
public void send(String email, String subject, String content)
        throws MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", Integer.toString(port));

    injectProperties(props);

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

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

    Transport.send(message);
}
项目:Free-Choice.Net    文件:MailSender.java   
private Session getSession(boolean getNew) {

    Authenticator pswAuth = new Authenticator() {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(senderAddr, senderPsw);
        }
    };
    if (getNew) {
        session = Session.getInstance(sessionConfig, pswAuth);
    } else {
        if (session == null) {
            session = Session.getInstance(sessionConfig, pswAuth);
        }
    }
    session.setDebug(debugMode);
    return session;
}
项目:anycook-api    文件:MailHandler.java   
/**
 * Konstruktor. Erstellt allgemeine Properties zum versenden
 */
private MailHandler() {

    logger = LogManager.getLogger(getClass());
    executor = Executors.newFixedThreadPool(10);


    Properties props = new Properties();
    props.put("mail.smtps.auth", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.host", Configuration.getInstance().getSMTPHost());
    props.put("mail.smtp.socketFactory.port", Configuration.getInstance().getSMTPPort());


    Authenticator auth = new SMTPAuthenticator();
    session = Session.getInstance(props, auth);
    session.setDebug(false);
}