• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Java Session类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中javax.mail.Session的典型用法代码示例。如果您正苦于以下问题:Java Session类的具体用法?Java Session怎么用?Java Session使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Session类属于javax.mail包,在下文中一共展示了Session类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: getEmail

import javax.mail.Session; //导入依赖的package包/类
public void getEmail() throws MessagingException, IOException {
    Session session = Session.getDefaultInstance(System.getProperties(),null);
    Store store = null;
    store = session.getStore("imaps");

    // store.connect(this.host, this.userName, this.password);

    // Get default folder
    Folder folder = store.getDefaultFolder();
    folder.getMessages();
    folder.getNewMessageCount();
    Message m = folder.getMessage(0);
    m.getMessageNumber();
    m.getAllRecipients();
    m.getReceivedDate();
    m.getFrom();
    m.getSubject();
    m.getReplyTo();
    m.getContent();
    m.getSize();

    // Get any folder by name
    Folder[] folderList = folder.list();
}
 
开发者ID:victordiaz,项目名称:phonk,代码行数:25,代码来源:PNetwork.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: sendTextEmail

import javax.mail.Session; //导入依赖的package包/类
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);
    }
}
 
开发者ID:Alfresco,项目名称:alfresco-greenmail,代码行数:18,代码来源:GreenMailUtil.java


示例4: sendEmail

import javax.mail.Session; //导入依赖的package包/类
@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);
}
 
开发者ID:transwarpio,项目名称:rapidminer,代码行数:23,代码来源:MailSenderSMTP.java


示例5: sendMail

import javax.mail.Session; //导入依赖的package包/类
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);
	}
}
 
开发者ID:vishal1997,项目名称:DiscussionPortal,代码行数:33,代码来源:SendMail.java


示例6: authorizeWebShopEmail

import javax.mail.Session; //导入依赖的package包/类
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;
}
 
开发者ID:xSzymo,项目名称:Spring-web-shop-project,代码行数:23,代码来源:EmailActions.java


示例7: getMailSession

import javax.mail.Session; //导入依赖的package包/类
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;
}
 
开发者ID:bsteker,项目名称:bdf2,代码行数:22,代码来源:EmailSender.java


示例8: testAttachmentExtraction

import javax.mail.Session; //导入依赖的package包/类
/**
 * Test attachment extraction with a TNEF message
 * @throws Exception
 */
public void testAttachmentExtraction() throws Exception
{
    AuthenticationUtil.setRunAsUserSystem();
    /**
     * Load a TNEF message
     */
    ClassPathResource fileResource = new ClassPathResource("imap/test-tnef-message.eml");
    assertNotNull("unable to find test resource test-tnef-message.eml", fileResource);
    InputStream is = new FileInputStream(fileResource.getFile());
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()), is);

    NodeRef companyHomeNodeRef = findCompanyHomeNodeRef();

    FileInfo f1 = fileFolderService.create(companyHomeNodeRef, "ImapServiceImplTest", ContentModel.TYPE_FOLDER);
    FileInfo f2 = fileFolderService.create(f1.getNodeRef(), "test-tnef-message.eml", ContentModel.TYPE_CONTENT);
    
    ContentWriter writer = fileFolderService.getWriter(f2.getNodeRef());
    writer.putContent(new FileInputStream(fileResource.getFile()));
    
    imapService.extractAttachments(f2.getNodeRef(), message);

    List<AssociationRef> targetAssocs = nodeService.getTargetAssocs(f2.getNodeRef(), ImapModel.ASSOC_IMAP_ATTACHMENTS_FOLDER);
    assertTrue("attachment folder is found", targetAssocs.size() == 1);
    NodeRef attachmentFolderRef = targetAssocs.get(0).getTargetRef();
    
    assertNotNull(attachmentFolderRef);

    List<FileInfo> files = fileFolderService.listFiles(attachmentFolderRef);
    assertTrue("three files not found", files.size() == 3);

}
 
开发者ID:Alfresco,项目名称:alfresco-repository,代码行数:36,代码来源:ImapServiceImplTest.java


示例9: getSession

import javax.mail.Session; //导入依赖的package包/类
/**
 * 获取用户与邮件服务器的连接
 *
 * @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;
}
 
开发者ID:FlyingHe,项目名称:UtilsMaven,代码行数:27,代码来源:MailUtils.java


示例10: setup

import javax.mail.Session; //导入依赖的package包/类
@Before
public void setup() throws Exception {

    // container.enableInterfaceMocking(true);
    if (!NamingManager.hasInitialContextFactoryBuilder()) {
        NamingManager
                .setInitialContextFactoryBuilder(new TestNamingContextFactoryBuilder());
    }
    InitialContext initialContext = new InitialContext();
    Properties properties = new Properties();
    properties.put("mail.smtp.from", "[email protected]");
    mailMock = Session.getInstance(properties);
    initialContext.bind("java:openejb/Resource/" + DEFAULT_MAIL_RESOURCE, mailMock);
    configurationService = mock(APPConfigurationServiceBean.class);
    commService = spy(new APPCommunicationServiceBean());
    commService.configService = configurationService;
    doNothing().when(commService).transportMail(
            Matchers.any(MimeMessage.class));
}
 
开发者ID:servicecatalog,项目名称:oscm,代码行数:20,代码来源:APPCommunicationServiceBeanTest.java


示例11: processMessage

import javax.mail.Session; //导入依赖的package包/类
public void processMessage()
{
	System.out.println("Process message");
	try
	{
		Session session = Session.getDefaultInstance(new Properties());
		InputStream inputStream = new ByteArrayInputStream(message.getBytes());
		MimeMessage mimeMessage = new MimeMessage(session,inputStream);
		if(mimeMessage.isMimeType(InboxVariables.plainMime))
		{
			plainMessage = mimeMessage.getContent().toString();
		}
		else if(mimeMessage.isMimeType(InboxVariables.multipartMime))
		{
			MimeMultipart mimeMultipart = (MimeMultipart) mimeMessage.getContent();
			processMimeMultipart(mimeMultipart);
		}
		subject = mimeMessage.getSubject();
		System.out.println("Message processed");
	}
	catch(Exception ex)
	{
		ex.printStackTrace(System.err);
	}
}
 
开发者ID:travispessetto,项目名称:OrigamiSMTP,代码行数:26,代码来源:Message.java


示例12: convert

import javax.mail.Session; //导入依赖的package包/类
public Email convert(RawData rawData) throws IOException {
    try {
        Session s = Session.getDefaultInstance(new Properties());
        MimeMessage mimeMessage = new MimeMessage(s, rawData.getContentAsStream());
        String subject = Objects.toString(mimeMessage.getSubject(), UNDEFINED);
        ContentType contentType = ContentType.fromString(mimeMessage.getContentType());
        Object messageContent = mimeMessage.getContent();

        switch (contentType) {
            case HTML:
            case PLAIN:
                return buildPlainOrHtmlEmail(rawData, subject, contentType, messageContent);
            case MULTIPART_ALTERNATIVE:
                return buildMultipartAlternativeMail(rawData, subject, (Multipart) messageContent);
            default:
                throw new IllegalStateException("Unsupported e-mail content type " + contentType.name());
        }
    } catch (MessagingException e) {
        return buildFallbackEmail(rawData);
    }
}
 
开发者ID:gessnerfl,项目名称:fake-smtp-server,代码行数:22,代码来源:EmailFactory.java


示例13: createMessage

import javax.mail.Session; //导入依赖的package包/类
private static Message createMessage(Session session)
        throws MessagingException, IOException {
    Message msg = new MimeMessage(session);
    InternetAddress fromAddress = new InternetAddress(
            getVal("from.mail"), getVal("username"));
    msg.setFrom(fromAddress);
    Optional.ofNullable(getVal("to.mail")).ifPresent((String tos) -> {
        for (String to : tos.split(";")) {
            try {
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
                        to, to));
            } catch (Exception ex) {
                Logger.getLogger(Mailer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });

    msg.setSubject(parseSubject(getVal("msg.subject")));
    msg.setContent(getMessagePart());
    return msg;
}
 
开发者ID:CognizantQAHub,项目名称:Cognizant-Intelligent-Test-Scripter,代码行数:22,代码来源:Mailer.java


示例14: lookupSessionInJNDI

import javax.mail.Session; //导入依赖的package包/类
private Session lookupSessionInJNDI() {
    addInfo("Looking up javax.mail.Session at JNDI location ["
            + jndiLocation + "]");

    try {
        Context initialContext = new InitialContext();
        Object obj = initialContext.lookup(jndiLocation);

        return (Session) obj;
    } catch (Exception e) {
        addError("Failed to obtain javax.mail.Session from JNDI location ["
                + jndiLocation + "]");

        return null;
    }
}
 
开发者ID:zhaojunfei,项目名称:lemon,代码行数:17,代码来源:SMTPAppenderBase.java


示例15: getSession

import javax.mail.Session; //导入依赖的package包/类
/**
 *
 * This method will create a new Mail Session
 *
 * @param smtpServer
 *            Mail server IP/FQDN
 * @param port
 *            SMTP port
 * @param sendFrom
 *            Sender's Email ID
 * @param password
 *            Email account Password
 * @param sendTo
 *            Receiver's Email address
 * @return
 *         Mail Session Object with Properties configured
 */
private static Session getSession(String smtpServer, String port, final String sendFrom, final String password) {
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpServer);
    props.put("java.net.preferIPv4Stack", "true");
    props.put("mail.smtp.port", port);

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

    if (!StringUtils.isBlank(password)) {
        props.put("mail.smtp.socketFactory.port", port);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");

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

    return session;
}
 
开发者ID:opensecuritycontroller,项目名称:osc-core,代码行数:41,代码来源:EmailUtil.java


示例16: sendToAdmin

import javax.mail.Session; //导入依赖的package包/类
@Override
public boolean sendToAdmin(final String institutionEmailAddress, final String applicationMessage) {
    String[] to = new String[]{"[email protected]"};
    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(APPLICATION_SUBJECT);
        message.setText(applicationBody + "Email: " + institutionEmailAddress + "\nMessage: " + applicationMessage);
        Transport transport = session.getTransport("smtp");
        transport.connect(host, username, password);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        LOGGER.info("Email sent to Admin");
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
开发者ID:blmalone,项目名称:Blockchain-Academic-Verification-Service,代码行数:32,代码来源:EmailService.java


示例17: getMailSession

import javax.mail.Session; //导入依赖的package包/类
/**
    * Creates a mail session with authentication if it is required, ie if it has been set up with SMTP authentication
    * in the config page
    *
    * @param properties
    * @return
    */
   public static Session getMailSession() {
String smtpServer = Configuration.get(ConfigurationKeys.SMTP_SERVER);
Properties properties = new Properties();
properties.put("mail.smtp.host", smtpServer);

String smtpAuthUser = Configuration.get(ConfigurationKeys.SMTP_AUTH_USER);
String smtpAuthPass = Configuration.get(ConfigurationKeys.SMTP_AUTH_PASSWORD);
Session session = null;
if (StringUtils.isBlank(smtpAuthUser)) {
    session = Session.getInstance(properties);
} else {
    properties.setProperty("mail.smtp.submitter", smtpAuthUser);
    properties.setProperty("mail.smtp.auth", "true");
    SMTPAuthenticator auth = new SMTPAuthenticator(smtpAuthUser, smtpAuthPass);
    session = Session.getInstance(properties, auth);
}
return session;
   }
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:26,代码来源:Emailer.java


示例18: createMimeMessage

import javax.mail.Session; //导入依赖的package包/类
public static boolean createMimeMessage() {
	try {
		// 用props对象来创建并初始化session对象
		session = Session.getDefaultInstance(props, null);
		// 用session对象来创建并初始化邮件对象
		message = new MimeMessage(session);
		// 生成附件组件的实例
		mp = new MimeMultipart();
	} catch (Exception e) {
		return false;
	}
	return true;
}
 
开发者ID:jiangzongyao,项目名称:kettle_support_kettle8.0,代码行数:14,代码来源:Message.java


示例19: createEmailMessage

import javax.mail.Session; //导入依赖的package包/类
/**
 * Bereitet den Mailinhalt zum Senden vor.
 *
 * @throws MessagingException -
 * @throws UnsupportedEncodingException -
 */
public void createEmailMessage() throws MessagingException, UnsupportedEncodingException {
    mailSession = Session.getDefaultInstance(emailProperties, null);
    emailMessage = new MimeMessage(mailSession);
    emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
    for (String toEmail : toEmailList) {
        emailMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(toEmail));
    }
    emailMessage.setSubject(emailSubject);
    emailMessage.setContent(emailBody, "text/html");
}
 
开发者ID:LCA311,项目名称:leoapp-sources,代码行数:18,代码来源:MailClient.java


示例20: initSession

import javax.mail.Session; //导入依赖的package包/类
private void initSession() {
    session = Session.getDefaultInstance(
        emailConfig,
        new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        }
    );
}
 
开发者ID:maillouxc,项目名称:git-rekt,代码行数:12,代码来源:EmailService.java



注:本文中的javax.mail.Session类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java ConfigurationProperties类代码示例发布时间:2022-05-20
下一篇:
Java IdentityHashMap类代码示例发布时间:2022-05-20
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap