當前位置: 首頁>>代碼示例>>Java>>正文


Java Session.getInstance方法代碼示例

本文整理匯總了Java中javax.mail.Session.getInstance方法的典型用法代碼示例。如果您正苦於以下問題:Java Session.getInstance方法的具體用法?Java Session.getInstance怎麽用?Java Session.getInstance使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在javax.mail.Session的用法示例。


在下文中一共展示了Session.getInstance方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: sendMail

import javax.mail.Session; //導入方法依賴的package包/類
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);
}
 
開發者ID:bndynet,項目名稱:web-framework-for-java,代碼行數:24,代碼來源:MailHelper.java

示例2: sendMsg

import javax.mail.Session; //導入方法依賴的package包/類
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;
	}

}
 
開發者ID:ICT-BDA,項目名稱:EasyML,代碼行數:27,代碼來源:JavaMail.java

示例3: sendAttachMail

import javax.mail.Session; //導入方法依賴的package包/類
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;
    }
}
 
開發者ID:JamesLiAndroid,項目名稱:AndroidKillerService,代碼行數:33,代碼來源:SimpleMailSender.java

示例4: sendMail

import javax.mail.Session; //導入方法依賴的package包/類
private void sendMail(String subject, String body, MailSettings settings) throws MessagingException {

        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", settings.getSmtpServer());
        props.put("mail.smtp.port", settings.getSmtpPort() + "");

        if (settings.getMode() == MailSettings.Mode.SSL) {
            props.put("mail.smtp.socketFactory.port", settings.getSmtpPort() + "");
            props.put("mail.smtp.socketFactory.class",
                    "javax.net.ssl.SSLSocketFactory");
        } else if (settings.getMode() == MailSettings.Mode.TLS) {
            props.put("mail.smtp.starttls.enable", "true");
        }

        props.put("mail.smtp.auth", settings.isUseAuth() + "");

        Session session;
        if (settings.isUseAuth()) {
            session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(settings.getUser(), settings.getPass());
                }
            });
        } else {
            session = Session.getInstance(props);
        }

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(settings.getFrom()));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(settings.getTo()));
        message.setSubject(subject);
        message.setText(body);

        Transport.send(message);

    }
 
開發者ID:dainesch,項目名稱:HueSense,代碼行數:41,代碼來源:MailService.java

示例5: testSetSession

import javax.mail.Session; //導入方法依賴的package包/類
@Test
public void testSetSession()
{
	smsTestClient.initializeSMSClient("Memoranda", "8005551212", "T-Mobile");
	Session testSession;
	props = new Properties();
	props.put("mail.smtp.auth", "true");
	props.put("mail.smtp.starttls.enable", "true");
	props.put("mail.smtp.host", "outlook.office365.com");
	props.put("mail.smtp.port", "587");
	testSession = Session.getInstance(props, new javax.mail.Authenticator()
	{
		protected PasswordAuthentication getPasswordAuthentication() 
		{
			return new PasswordAuthentication(smsTestClient.getUsername(), smsTestClient.getPassword());
		}
});
	smsTestClient.setSession(testSession);
}
 
開發者ID:ser316asu,項目名稱:Wilmersdorf_SER316,代碼行數:20,代碼來源:SMS_Test.java

示例6: ImapStorage

import javax.mail.Session; //導入方法依賴的package包/類
/**
 * Instantiate the IMAP storage
 *
 * @param imapServerHost    the IMAP server host name
 */
public ImapStorage( String imapServerHost ) {

    this.imapServerHost = imapServerHost;

    // set the session
    Properties props = new Properties();
    props.setProperty("mail.smtp.host", this.imapServerHost);
    props.setProperty("mail.imap.partialfetch", "false");
    props.setProperty("mail.smtp.connectiontimeout", String.valueOf(CONNECTION_TIMEOUT));
    props.setProperty("mail.smtp.timeout", String.valueOf(TIMEOUT));

    // add custom mail properties from RBVConfigurator
    Map<String, String> customMailProperties = RbvConfigurator.getInstance().getProperties("mail.");
    for (Entry<String, String> mailProperty : customMailProperties.entrySet()) {
        props.setProperty(mailProperty.getKey(), mailProperty.getValue());
    }

    this.session = Session.getInstance(props);
    if (log.isTraceEnabled()) {
        session.setDebug(true);
    }

    log.debug("IMAP session to host '" + imapServerHost + "' initialized");
}
 
開發者ID:Axway,項目名稱:ats-framework,代碼行數:30,代碼來源:ImapStorage.java

示例7: initSession

import javax.mail.Session; //導入方法依賴的package包/類
/**
 * Initialize the SMTP session
 *
 * @throws ActionException
 */
private void initSession() throws ActionException {

    // initialize the mail session with the current properties
    session = Session.getInstance(mailProperties);
    // user can get more debug info with the session's debug mode
    session.setDebug(configurator.getMailSessionDebugMode());

    // initialize the SMPT transport
    try {
        transport = session.getTransport("smtp");
    } catch (NoSuchProviderException e) {
        throw new ActionException(e);
    }
}
 
開發者ID:Axway,項目名稱:ats-framework,代碼行數:20,代碼來源:MailSender.java

示例8: getSession

import javax.mail.Session; //導入方法依賴的package包/類
/**
 * Create session based on the mail properties.
 *
 * @return session session from mail properties
 */
private Session getSession() {
	final Properties props = new Properties();

	props.setProperty("mail.smtp.host", mailProperties.getString("mail.smtp.host"));

	String auth = "true";
	if (mailProperties.containsKey("mail.smtp.auth")) {
		auth = mailProperties.getString("mail.smtp.auth");
	}
	props.setProperty("mail.smtp.auth", auth);

	props.setProperty("mail.smtp.port", mailProperties.getString("mail.smtp.port"));

	String starttls = "true";
	if (mailProperties.containsKey("mail.smtp.starttls.enable")) {
		starttls = mailProperties.getString("mail.smtp.starttls.enable");
	}
	props.put("mail.smtp.starttls.enable", starttls);

	props.put("mail.debug", mailProperties.getString("mail.debug"));
	props.put("mail.smtp.socketFactory.class", mailProperties.getString("mail.smtp.socketFactory.class"));
	props.put("mail.smtp.socketFactory.fallback", mailProperties.getString("mail.smtp.socketFactory.fallback"));
	props.put("mail.smtp.socketFactory.port", mailProperties.getString("mail.smtp.socketFactory.port"));

	return Session.getInstance(props, new SMTPAuthenticator());
}
 
開發者ID:daima,項目名稱:solo-spring,代碼行數:32,代碼來源:MailService.java

示例9: OkMailClient

import javax.mail.Session; //導入方法依賴的package包/類
private OkMailClient(Builder builder) {
    this.host = builder.host;
    this.port = builder.port;
    this.protocol = builder.protocol;
    this.username = builder.username;
    this.password = builder.password;
    this.auth = builder.auth;
    this.ssl = builder.ssl;
    this.debug = builder.debug;
    this.mailer = builder.mailer;
    this.session = Session.getInstance(getConfig(), new DefaultAuthenticator(this.username, this.password));
    if (debug) {
        this.session.setDebug(true);
    }
}
 
開發者ID:TFdream,項目名稱:okmail,代碼行數:16,代碼來源:OkMailClient.java

示例10: connect

import javax.mail.Session; //導入方法依賴的package包/類
public static Boolean connect(Properties props)
        throws MessagingException, IOException {
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(
                    props.getProperty("username"),
                    props.getProperty("password"));
        }
    });
    Transport transport = session.getTransport("smtp");
    transport.connect();
    transport.close();
    return true;
}
 
開發者ID:CognizantQAHub,項目名稱:Cognizant-Intelligent-Test-Scripter,代碼行數:16,代碼來源:Mailer.java

示例11: sendout

import javax.mail.Session; //導入方法依賴的package包/類
/**
 * 發送郵件
 * 
 * @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;
	}
}
 
開發者ID:tb544731152,項目名稱:iBase4J,代碼行數:38,代碼來源:EmailSender.java

示例12: getEmailSession

import javax.mail.Session; //導入方法依賴的package包/類
/**
 * Retrieves a email session based on the passed properties.
 * 
 * @param unProperties
 *            define the settings of the session.
 * @return a email session for the passed properties.
 */
private Session getEmailSession(Properties unProperties) {
    String mailServer = unProperties.getProperty(HandlerUtils.MAIL_SERVER);
    String returnAddress = unProperties
            .getProperty(HandlerUtils.MAIL_RESPONSE_ADDRESS);

    HandlerUtils.checkNotNull(mailServer, HandlerUtils.MAIL_SERVER);
    HandlerUtils.checkNotNull(returnAddress,
            HandlerUtils.MAIL_RESPONSE_ADDRESS);

    String mailPort = unProperties.getProperty(HandlerUtils.MAIL_PORT);
    String username = unProperties.getProperty(HandlerUtils.MAIL_USER);
    String password = unProperties.getProperty(HandlerUtils.MAIL_USER_PWD);

    Properties emailProperties = new Properties();
    emailProperties.setProperty("mail.smtp.host", mailServer);
    emailProperties.put("mail.smtp.from", returnAddress);

    if ((mailPort != null) && mailPort.length() > 0) {
        emailProperties.put("mail.smtp.port", mailPort);
    }

    SMTPAuthenticator authenticator;

    if (username != null && username.length() > 0 && password != null) {
        authenticator = new SMTPAuthenticator(username, password);
        emailProperties.put("mail.smtp.auth", "true");
    } else {
        authenticator = null;
    }

    return Session.getInstance(emailProperties, authenticator);
}
 
開發者ID:servicecatalog,項目名稱:oscm,代碼行數:40,代碼來源:UserNotificationHandler.java

示例13: MimePackage

import javax.mail.Session; //導入方法依賴的package包/類
/**
 * Create an empty MIME package - use the add* methods to manipulate it
 *
 * @throws PackageException
 */
@PublicAtsApi
public MimePackage() throws PackageException {

    this.message = new MimeMessage(Session.getInstance(new Properties()));
    try {
        this.message.setContent(new MimeMultipart());
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
    this.subjectCharset = null;
}
 
開發者ID:Axway,項目名稱:ats-framework,代碼行數:17,代碼來源:MimePackage.java

示例14: emailPassword

import javax.mail.Session; //導入方法依賴的package包/類
private boolean emailPassword(String password, String username, String email) {
    /* Default to protocol smtp when SmtpEncryption is set to "None" */
    String prot = "smtp";

    if (settingsService.getSmtpServer() == null || settingsService.getSmtpServer().isEmpty()) {
        LOG.warn("Can not send email; no Smtp server configured.");
        return false;
    }

    Properties props = new Properties();
    if (settingsService.getSmtpEncryption().equals("SSL/TLS")) {
        prot = "smtps";
        props.put("mail." + prot + ".ssl.enable", "true");
    } else if (settingsService.getSmtpEncryption().equals("STARTTLS")) {
        prot = "smtp";
        props.put("mail." + prot + ".starttls.enable", "true");
    }
    props.put("mail." + prot + ".host", settingsService.getSmtpServer());
    props.put("mail." + prot + ".port", settingsService.getSmtpPort());
    /* use authentication when SmtpUser is configured */
    if (settingsService.getSmtpUser() != null && !settingsService.getSmtpUser().isEmpty()) {
        props.put("mail." + prot + ".auth", "true");
    }

    Session session = Session.getInstance(props, null);

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(settingsService.getSmtpFrom()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject("Airsonic Password");
        message.setText("Hi there!\n\n" +
                "You have requested to reset your Airsonic password.  Please find your new login details below.\n\n" +
                "Username: " + username + "\n" +
                "Password: " + password + "\n\n" +
                "--\n" +
                "Your Airsonic server\n" +
                "airsonic.github.io/");
        message.setSentDate(new Date());

        Transport trans = session.getTransport(prot);
        try {
            if (props.get("mail." + prot + ".auth") != null && props.get("mail." + prot + ".auth").equals("true")) {
                trans.connect(settingsService.getSmtpServer(), settingsService.getSmtpUser(), settingsService.getSmtpPassword());
            } else {
                trans.connect();
            }
            trans.sendMessage(message, message.getAllRecipients());
        } finally {
            trans.close();
        }
        return true;

    } catch (Exception x) {
        LOG.warn("Failed to send email.", x);
        return false;
    }
}
 
開發者ID:airsonic,項目名稱:airsonic,代碼行數:59,代碼來源:RecoverController.java

示例15: Send

import javax.mail.Session; //導入方法依賴的package包/類
/**
 * Send email using GMail SMTP server.
 *
 * @param username GMail username
 * @param password GMail password
 * @param recipientEmail TO recipient
 * @param ccEmail CC recipient. Can be empty if there is no CC recipient
 * @param title title of the message
 * @param message message to be sent
 * @throws AddressException if the email address parse failed
 * @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
 */
private static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException, EmailInesistente {
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    // Get a Properties object
    Properties props = System.getProperties();
    props.setProperty("mail.smtps.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.setProperty("mail.smtps.auth", "true");

    /*
    If set to false, the QUIT command is sent and the connection is immediately closed. If set 
    to true (the default), causes the transport to wait for the response to the QUIT command.

    ref :   http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html
            http://forum.java.sun.com/thread.jspa?threadID=5205249
            smtpsend.java - demo program from javamail
    */
    props.put("mail.smtps.quitwait", "false");

    Session session = Session.getInstance(props, null);

    // -- Create a new message --
    final MimeMessage msg = new MimeMessage(session);

    // -- Set the FROM and TO fields --
    msg.setFrom(new InternetAddress(username + "@gmail.com"));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));

    if (ccEmail.length() > 0) {
        msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
    }

    msg.setSubject(title);
    msg.setText(message, "utf-8");
    msg.setSentDate(new Date());

    SMTPTransport t = (SMTPTransport)session.getTransport("smtps");

    t.connect("smtp.gmail.com", username, password);
    try{
        t.sendMessage(msg, msg.getAllRecipients()); 
    }
    catch (SendFailedException e){
        throw new EmailInesistente();
    }
    t.close();
}
 
開發者ID:IngSW-unipv,項目名稱:Progetto-A,代碼行數:64,代碼來源:Email.java


注:本文中的javax.mail.Session.getInstance方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。