Could not establish the connection to the Exchange Web Service - Java API - java

I am testing the Microsoft Exchange Web Service Java API (version 1.2) to read mails from a server. Here is my code:
String url = "https://my-server/EWS/exchange.asmx";
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.setTraceEnabled(true);
service.setCredentials(new WebCredentials("user", "password"));
service.setUrl(url.toURI());
Mailbox mailbox = new Mailbox("foo#bar.com");
FolderId folder = new FolderId(WellKnownFolderName.Inbox, mailbox);
ItemView view = new ItemView(10);
view.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Descending);
FindItemsResults<Item> items = service.findItems(folder, view);
Unfortunately, this code throws the following error:
Exception in thread "main" microsoft.exchange.webservices.data.EWSHttpException: Connection not established
at microsoft.exchange.webservices.data.HttpClientWebRequest.throwIfConnIsNull(Unknown Source)
at microsoft.exchange.webservices.data.HttpClientWebRequest.getResponseCode(Unknown Source)
at microsoft.exchange.webservices.data.EwsUtilities.formatHttpResponseHeaders(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeServiceBase.traceHttpResponseHeaders(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeServiceBase.processHttpResponseHeaders(Unknown Source)
at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(Unknown Source)
at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeService.findItems(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeService.findItems(Unknown Source)
at foo.bar.TestMail.main(TestMail.java:52)
I'm not able to understand what is wrong with the current code. Do you have any clue, or at least some tests to try?
Note that the web-service (https//my-server/exchange.asmx) is accessible to my Java code.
Not sure if it can help, but I've found that in the traces displayed by the logs:
<Trace Tag="EwsResponse" Tid="1" Time="2013-01-28 10:47:03Z">
<html><head><title>Error</title></head><body>The function requested is not supported
</body></html>
</Trace>
EDIT
I've made another test. This time, I use the defaults credentials - so my own email account - using service.setUseDefaultCredentials(true); instead of setting the WebCredentials object. The connection is still not established, but I get another error (I've took only the interesting part of the trace log):
<h1>You are not authorized to view this page</h1>
You do not have permission to view this directory or page using the credentials that you supplied because your Web browser is sending a WWW-Authenticate header field that the Web server is not configured to accept.
(...)
<h2>HTTP Error 401.2 - Unauthorized: Access is denied due to server configuration.<br>Internet Information Services (IIS)</h2>
Of course, I can't access nor change anything on the Exchange server side. Is there a way to make the authentication successful?

The problem is due to the authentication scheme used. By default, EWS uses NTLM, but my Exchange server is not configured to accept this kind of authentication. I have to use LDAP authentication.

I got the above mentioned error and spend many hours trying to fix it. My ultimate solution was to give up on EWS Version 1.2 completely and use the following javax.mail code like this:
package javaapplication4;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
public class JavaApplication4 {
public static void main(String[] args) throws Exception {
new JavaApplication4().send_email();
}
private void send_email() throws Exception
{
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.yourserver.net");
props.put("mail.from", "yourusername#youremailaddress.com");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.enable", "false");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "587");
Authenticator authenticator = new Authenticator();
props.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
Session session = Session.getInstance(props, authenticator);
MimeMessage msg = new MimeMessage(session);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO, "yourusername#youremailaddress.com");
// also tried #gmail.com
msg.setSubject("JavaMail ssl test");
msg.setSentDate(new Date());
msg.setText("Hello, world!\n");
Transport transport;
transport = session.getTransport("smtp");
transport.connect();
msg.saveChanges();
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
}
private class Authenticator extends javax.mail.Authenticator {
private PasswordAuthentication authentication;
public Authenticator() {
String username = "yourusername#youremailaddress.com";
String password = "yourpassword";
authentication = new PasswordAuthentication(username, password);
}
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
}
}
You will need to get the javamail-1.4.7 and load the mail.jar from (http://www.oracle.com/technetwork/java/index-138643.html) into the project.
One thing we did which shed light on the situation is download Thunderbird mail client which can auto-discover information about the exchange server to make sure all of our settings were right.

This is an Example of EWS JAVA api 1.2,This is one of the ways you can try
package com.ea.connector.exchange;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import microsoft.exchange.webservices.data.BasePropertySet;
import microsoft.exchange.webservices.data.ExchangeCredentials;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.FindItemsResults;
import microsoft.exchange.webservices.data.Item;
import microsoft.exchange.webservices.data.ItemSchema;
import microsoft.exchange.webservices.data.ItemView;
import microsoft.exchange.webservices.data.LogicalOperator;
import microsoft.exchange.webservices.data.OffsetBasePoint;
import microsoft.exchange.webservices.data.PropertySet;
import microsoft.exchange.webservices.data.SearchFilter;
import microsoft.exchange.webservices.data.SortDirection;
import microsoft.exchange.webservices.data.WebCredentials;
import microsoft.exchange.webservices.data.WebProxy;
import microsoft.exchange.webservices.data.WellKnownFolderName;
import org.apache.commons.httpclient.NTCredentials;
import com.ea.connector.exchange.bean.ExchangeConnectionParamBean;
import com.ea.connector.exchange.util.ExchMessageProperties;
import com.ea.connector.net.ExchGetItemRequest;
public class Test {
protected static ArrayList<String> propertiesToFetch = new ArrayList<String>();
private static ExchangeService mService;
// private Settings mSettings;
//
// private int imailCount;
private Date dStartDate;
private Date dEndDate;
private static ExchangeConnectionParamBean objParamBean;
public void setPropertiesToBeFetched(List<String> filter) {
propertiesToFetch.addAll(filter);
}
public Date getConnectorStartDate() {
return dStartDate;
}
public void setConnectorStartDate(Date dStartDate) {
this.dStartDate = dStartDate;
}
public ExchangeConnectionParamBean getParamBean() {
return objParamBean;
}
public void setParambean(ExchangeConnectionParamBean objParambean) {
Test.objParamBean = objParambean;
}
public Date getConnectorEndDate() {
return dEndDate;
}
public void setConnectorEndDate(Date dEndDate) {
this.dEndDate = dEndDate;
}
public static void main(String []args) throws URISyntaxException,Exception
{
setCredentialsAndGetExchRequest();
System.out.println("conncection established");
}
protected static ExchGetItemRequest setCredentialsAndGetExchRequest() throws URISyntaxException,Exception{
#SuppressWarnings("unused")
FindItemsResults<Item> resultMails;
mService = new ExchangeService();
mService.setUrl(new URI("https://outlook.office365.com/EWS/Exchange.asmx"));
WebProxy paramWebProxy=new WebProxy("ptbproxy.domain.com",8080);
mService.setWebProxy(paramWebProxy);
ExchangeCredentials cred = new WebCredentials("EA_Test_mailbox#domain.com","Zuxu0000");
NTCredentials ntCredentials = new NTCredentials("EA_Test_mailbox#domain.com","Zuxu0000", "",
"");
mService.setCredentials(cred);
// ProxyHost httpProxy=new ProxyHost("ptbproxy.domain.com",8080);
// UsernamePasswordCredentials cred1=new UsernamePasswordCredentials("EA_Test_mailbox#domain.com","Zuxu0000");
// ExchGetItemRequest req = new ExchGetItemRequest(String.valueOf(new URI("http://outlook.office365.com/EWS/Exhanges.asmx")),ntCredentials);
ExchGetItemRequest req = new ExchGetItemRequest("https://outlook.office365.com/EWS/Exhange.asmx",ntCredentials);
SearchFilter filter = getSearchFilter();
PropertySet propertySet = new PropertySet(BasePropertySet.IdOnly);
ItemView itemView = new ItemView(1000, 0, OffsetBasePoint.Beginning);
itemView.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Descending);
itemView.setPropertySet(propertySet);
//mService.setTimeout(500000);
req.setProperties(new ExchMessageProperties().getExchMessageProperties(propertiesToFetch));
/*Fetching of mail ids start here*/
resultMails = getMails(filter, itemView);
return req;
}
protected static SearchFilter getSearchFilter() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date d1 = sdf.parse("2014-11-04 00:00:00");
Date d2 = sdf.parse("2014-11-05 00:00:00");
SearchFilter greaterThanEq = new SearchFilter.IsGreaterThanOrEqualTo(
ItemSchema.DateTimeReceived,sdf.format(d1));
SearchFilter lessThan = new SearchFilter.IsLessThan(
ItemSchema.DateTimeReceived, sdf.format(d2));
SearchFilter mailFilter = new SearchFilter.IsEqualTo(
ItemSchema.ItemClass, "IPM.Note");
return new SearchFilter.SearchFilterCollection(LogicalOperator.And,
greaterThanEq, lessThan, mailFilter);
}
private static FindItemsResults<Item> getMails(SearchFilter searchFilter,
ItemView itemView) throws Exception {
FindItemsResults<Item> items = null;
int count = 0;
int maxTries = 3;
while (true) {
try {
items = mService.findItems(WellKnownFolderName.Inbox,
searchFilter, itemView);
break;
} catch (Exception e) {
if (++count == maxTries)
throw e;
}
}
return items;
}
}

Related

I have imported an project to eclipse wen i try to run the project i got one simple error am new to this so unable to rectify it

Error 1:
Description Resource Path Location Type The project was not built
since its build path is incomplete. Cannot find the class file for
java.util.Map$Entry. Fix the build path then try building this project
EmailSendingWebApp Unknown Java Problem
error 2 :
Description Resource Path Location Type The type java.util.Map$Entry
cannot be resolved. It is indirectly referenced from required .class
files EmailUtility.java /EmailSendingWebApp/src/net/codejava/email
line 29 Java Problem
This is my code:
code 1 : package net.codejava.email;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* A utility class for sending e-mail messages
* #author www.codejava.net
*
*/
public class EmailUtility {
public static void sendEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) 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);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);
// sends the e-mail
Transport.send(msg);
}
}
code 2 :
package net.codejava.email;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* A servlet that takes message details from user and send it as a new e-mail
* through an SMTP server.
*
* #author www.codejava.net
*
*/
#WebServlet("/EmailSendingServlet")
public class EmailSendingServlet extends HttpServlet {
private String host;
private String port;
private String user;
private String pass;
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
host = context.getInitParameter("host");
port = context.getInitParameter("port");
user = context.getInitParameter("user");
pass = context.getInitParameter("pass");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// reads form fields
String recipient = request.getParameter("recipient");
String subject = request.getParameter("subject");
String content = request.getParameter("content");
String resultMessage = "";
try {
EmailUtility.sendEmail(host, port, user, pass, recipient, subject,
content);
resultMessage = "The e-mail was sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
} finally {
request.setAttribute("Message", resultMessage);
getServletContext().getRequestDispatcher("/Result.jsp").forward(
request, response);
}
}
}
I am new to eclipse so I don't know how to link these two files, please help. Thanks.
Eclipse can compile Java projects against different installed JREs. Unless care is taken, the project's reference to its JRE is not portable. Verify that your Installed JREs preference page is pointing to something valid, then edit the project's Java Build Path so that it's referring to a valid JRE.
http://help.eclipse.org/neon/topic/org.eclipse.jdt.doc.user/reference/preferences/java/debug/ref-installed_jres.htm
http://help.eclipse.org/neon/topic/org.eclipse.jdt.doc.user/reference/ref-properties-build-path.htm?cp=1_4_3_1

How to let javamail support http proxy

I found that javamail only support socks. Is there any solution I can use to support http proxy?
public class MailConnectionTest {
public static void main(String args[]) throws MessagingException {
Properties props = MailConnectionTest.getProperties();
Session session = Session.getDefaultInstance(props, null);
String protocol = "pop3";
String host = "pop.163.com";
String username = "email username";
String password = "1Qaz2wsx3edc&";
Store store = session.getStore(protocol);
store.connect(host, username, password);
System.out.println("Success");
}
private static Properties getProperties() {
Properties props = System.getProperties();
props.put("mail.debug", "false");
// Proxy
props.put("proxySet", "true");
props.put("http.proxyHost", "proxyAdderss");
props.put("http.proxyPort", "8080");
return props;
}
}
As per the latest release of Javamail API 1.6.2 , JavaMail supports accessing mail servers through a web proxy server and also authenticating to the proxy server. Please see my code below.
import java.io.IOException;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;
public class ReadMailProxy {
public static void receiveMail(String userName, String password) {
try {
String proxyIP = "124.124.124.14";
String proxyPort = "4154";
String proxyUser = "test";
String proxyPassword = "test123";
Properties prop = new Properties();
prop.setProperty("mail.imaps.proxy.host", proxyIP);
prop.setProperty("mail.imaps.proxy.port", proxyPort);
prop.setProperty("mail.imaps.proxy.user", proxyUser);
prop.setProperty("mail.imaps.proxy.password", proxyPassword);
Session eSession = Session.getInstance(prop);
Store eStore = eSession.getStore("imaps");
eStore.connect("imap.mail.yahoo.com", userName, password);
Folder eFolder = eStore.getFolder("Inbox");
eFolder.open(Folder.READ_WRITE);
Message messages[] = eFolder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
System.out.println(messages.length);
for (int i = messages.length - 3; i < messages.length - 2; i++) {
Message message = messages[i];
System.out.println("Email Number::" + (i + 1));
System.out.println("Subject::" + message.getSubject());
System.out.println("From::" + message.getFrom()[0]);
System.out.println("Date::" + message.getSentDate());
try {
Multipart multipart = (Multipart) message.getContent();
for (int x = 0; x < multipart.getCount(); x++) {
BodyPart bodyPart = multipart.getBodyPart(x);
String disposition = bodyPart.getDisposition();
if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT))) {
System.out.println("Mail have some attachment : ");
DataHandler handler = bodyPart.getDataHandler();
System.out.println("file name : " + handler.getName());
} else {
System.out.println(bodyPart.getContent());
}
}
} catch (Exception e) {
System.out.println("Content: " + message.getContent().toString());
}
message.setFlag(Flag.SEEN, true);
}
eFolder.close(true);
eStore.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
receiveMail("umesh#yahoo.com", "test123");
}
}
javamail api 1.6 supports web server proxy
set these properties
mail.protocol.proxy.host
mail.protocol.proxy.port
for smtp set as
mail.smtp.proxy.host
mail.smtp.proxy.port
See the JavaMail FAQ:
How do I configure JavaMail to work through my proxy server?
... Without such a SOCKS server, if you want to use JavaMail to access mail servers outside the firewall indirectly, you might be able to use a program such as Corkscrew or connect to tunnel TCP connections through an HTTP proxy server. JavaMail does not support direct access through an HTTP proxy web server.
The implementation only support basic authentication for web proxy. You can find the source code in com.sun.mail.util.SocketFetcher.
Since javamail support NTLM authentication already, it is not hard to support NTLM authentication for web proxy.

Java Mail Error In Sending Mails

I am using a program to send emails. The code works when I use some other mail server. but I need to use my company's email account to send email. And the email account is provided by gmail xxxx#companyname.com. When I change the mail host to `stmp.gmail.com, I encounter the following error:
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. st6sm11092256pbc.58
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1515)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1054)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:634)
at javax.mail.Transport.send0(Transport.java:189)
at javax.mail.Transport.send(Transport.java:118)
at Mail.sendMail(Mail.java:48)
at Test.main(Test.java:6)
The code is as follows
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class Email_Autherticator extends Authenticator {
String username = "xxxx#gmail";
String password = "xxxxx";
public Email_Autherticator() {
super();
}
public Email_Autherticator(String user,String pwd){
super();
username = user;
password = pwd;
}
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username,password);
}
}
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Mail {
private String host = "smtp.gmail.com";
private String mail_head_name = "this is head of this mail";
private String mail_head_value = "this is head of this mail";
private String mail_to = "xxxx#gmail.com";
private String mail_from = "xxxx#Comanyname.com";//using gmail server
private String mail_subject = "this is the subject of this test mail";
private String mail_body = "this is mail_body of this test mail";
private String personalName = "xxx";
public void sendMail() throws SendFailedException{
try {
Properties props = new Properties();
Authenticator auth = new Email_Autherticator();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
System.out.println(props);
Session session = Session.getDefaultInstance(props,auth);
MimeMessage message = new MimeMessage(session);
message.setContent("Hello","text/plain");
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);
System.out.println(message);
Transport.send(message);
System.out.println("Send Mail Ok!");
} catch (Exception e) {
e.printStackTrace();
}
//return flag;
}
}
You almost certainly just need to rework your code to add the properties defined in the JavaMail API - Sending email via Gmail SMTP example example.
You can probably get away with setting your props to this:
Properties properties = new Properties();
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
properties.setProperty("mail.smtp.port", "587");
properties.setProperty("mail.smtp.user", gmailUsername);
properties.setProperty("mail.smtp.password", gmailPassword);
As this seems to be for work--if you can--I suggest using Spring. It makes it a lot cleaner and easier to use. I just recently did something similar to this with Spring and Gmail SMTP.
You need to define below properties in your java code.
import below package
import java.util.Properties;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
and add following to your code:
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
Use javax.mail.authenticator to authenticate with gmail servers
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Try this should work for you.
If still having issues, refer this error doc:
https://pepipost.com/tutorials/common-javamail-smtp-errors/
for sending SMTP email using javaMail API

How to set Email Client in Java?

i'm trying the very simple Email Client in java.
When i launch the programe i have an error message:
Exception in thread "main" javax.mail.AuthenticationFailedException: EOF on socket
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:146)
at javax.mail.Service.connect(Service.java:297)
at javax.mail.Service.connect(Service.java:156)
at SimpleEmailClient2.main(SimpleEmailClient2.java:21)
Java Result: 1
Why?
i use Gmail account and i set the POP and IMAP enabled
What could be the possible error in my code?
Thank you
here is the code:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
public class SimpleEmailClient2 {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
String host = "pop.gmail.com";
String provider = "pop3";
Session session = Session.getDefaultInstance(props, new MailAuthenticator());
Store store = session.getStore(provider);
store.connect(host, null, null);
Folder inbox = store.getFolder("INBOX");
if (inbox == null) {
System.out.println("No INBOX");
System.exit(1);
}
inbox.open(Folder.READ_ONLY);
Message[] messages = inbox.getMessages();
for (int i = 0; i < messages.length; i++) {
System.out.println("Message " + (i + 1));
messages[i].writeTo(System.out);
}
inbox.close(false);
store.close();
}
}
class MailAuthenticator extends Authenticator {
public MailAuthenticator() {
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("email#gmail.com", "password");
}
}
I don't believe gmail supports the pop3 provider; you have to use pop3s instead. Otherwise this should work fine.
Oracle has information on connecting javamail to gmail here.
Specifically it looks like you're failing when trying to establish the connection, likely because you don't specify a username/password to connect to. Try connecting using something like:
store.connect(host, "user618111#gmail.com", "[myPassword]");

Execute a script on remote server from a java application authenticating via kerberos keytabs

This has been most likely answered earlier, but all my searches did not get me a definite answer. What I've got is a Java application that currently uses ssh keys to run a script on a remote machine and save the results. I'm in the process of changing this to a Kerberos authentication using keytabs. I have the keytab set up and tested it using a perl script. If someone could point me to examples that tell me how to use kerberos keytabs in a Java application, that would be very helpful.
Thanks,
Kiran
Here's a full implementation of using a keytab in Java.
import javax.security.auth.Subject;
import javax.security.auth.kerberos.KerberosPrincipal;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import java.security.Principal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class SecurityUtils {
public static class LoginConfig extends Configuration {
private String keyTabLocation;
private String servicePrincipalName;
private boolean debug;
public LoginConfig(String keyTabLocation, String servicePrincipalName, boolean debug) {
this.keyTabLocation = keyTabLocation;
this.servicePrincipalName = servicePrincipalName;
this.debug = debug;
}
#Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
HashMap<String, String> options = new HashMap<String, String>();
options.put("useKeyTab", "true");
options.put("keyTab", this.keyTabLocation);
options.put("principal", this.servicePrincipalName);
options.put("storeKey", "true");
options.put("doNotPrompt", "true");
if (this.debug) {
options.put("debug", "true");
}
options.put("isInitiator", "false");
return new AppConfigurationEntry[]{new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options),};
}
}
public static Subject loginAs(String keyTabLocation, String servicePrincipal) {
try {
LoginConfig loginConfig = new LoginConfig(keyTabLocation, servicePrincipal, true);
Set<Principal> princ = new HashSet<Principal>(1);
princ.add(new KerberosPrincipal(servicePrincipal));
Subject sub = new Subject(false, princ, new HashSet<Object>(), new HashSet<Object>());
LoginContext lc;
lc = new LoginContext("", sub, null, loginConfig);
lc.login();
return lc.getSubject();
} catch (LoginException e) {
e.printStackTrace();
}
return null;
}
}
The loginAs method will return you a Subject which can be used to execute a privileged action:
result = Subject.doAs(subject,
new PrivilegedExceptionAction<NamingEnumeration<SearchResult>>() {
public NamingEnumeration<SearchResult> run() throws NamingException {
return context.search(directoryBase, filterBuilder.toString(), searchCtls);
}
});

Categories