本文整理匯總了Java中javax.mail.Session類的典型用法代碼示例。如果您正苦於以下問題:Java Session類的具體用法?Java Session怎麽用?Java Session使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Session類屬於javax.mail包,在下文中一共展示了Session類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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();
}
示例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;
}
}
示例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);
}
}
示例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);
}
示例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);
}
}
示例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;
}
示例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;
}
示例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);
}
示例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;
}
示例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));
}
示例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);
}
}
示例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);
}
}
示例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;
}
示例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;
}
}
示例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;
}