Java Mail Delegation Access not working for Office 365 - jakarta-mail

If you see the commented line of code store.connect.... I am trying to access the shared mailbox through a usermail box [migrated to cloud] which has a delegate access on this shared mailbox. On running this I get
javax.mail.AuthenticationFailedException: LOGIN failed.
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:715)
at javax.mail.Service.connect(Service.java:364)
at com.adecco.smpt.TestSSL.main(TestSSL.java:26)
If I try to access user-mail box instead of shared mailbox everything works well. Is there a different syntax to access the SHARED MAILBOX in JAVA ?? Thanks in advance.
import java.util.Properties;
import javax.mail.*;
public class TestSSL {
public static void main(String[] args) {
Properties props = System.getProperties();
props.put("mail.imaps.auth.plain.disable", "true");
props.put("mail.smtp.ssl.enable", "true");
try {
Session session = Session.getInstance(props, null);
session.setDebug(true);
Store store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, "office 365 username/alias name of shared MAILBOX", "PASSWORD");
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for (Message message : messages) {
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(2);
}
}
}

First, fix these common mistakes.
It looks like this article has the information you need.

Related

Fetching all Microsoft Active Directory users in Domino Xpages NamePicker via java Agent

I'm working with LDAP Microsoft Active Directory and Domino server and quite new with this.
we've successfully fetched all Microsoft Active Directory users in Domino via java Agent and have printed all the user names in java debug console. For that referred this http://lotus-blogs.blogspot.in/2009/08/ldap-programming-using-domino-java-step.html link.
Now, i want to get all users in Domino Xpages NamePicker, so is this possible to get all users in Xpages NamePicker via java Agent?
As per we see that in Xpages NamePicker, we are able to fetch the Domino Users with the help of java beans.
Any kind of suggestion will be really Appreciated.
My java Agent is like following-
import lotus.domino.*;
public class JavaAgent extends AgentBase {
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
LDAPQuery.ldapconnect();
} catch(Exception e) {
e.printStackTrace();
}
}
}
AND
import javax.naming.*;
import javax.naming.directory.*;
import java.util.*;
public class LDAPQuery {
public static void ldapconnect(){
String isFound="0";
try {
System.out.println("inside try 1");
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "PROVIDER_URL");
env.put(Context.SECURITY_PRINCIPAL, "UserName");
env.put(Context.SECURITY_CREDENTIALS, "password");
// Create initial context
DirContext ctx = new InitialDirContext(env);
// Specify the ids of the attributes to return
String[] attrIDs = {"cn","mail"};
SearchControls ctls = new SearchControls();
ctls.setReturningAttributes(attrIDs);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "(&(objectCategory=person)(mail=*abc.com))";
System.out.println("filter defined");
// Search for objects that have those matching attributes
NamingEnumeration answer = ctx.search("", filter,ctls);
System.out.println("get the answer!");
try {
System.out.println("inside try2");
while (answer.hasMore())
{
SearchResult sr = (SearchResult)answer.next();
System.out.println("<<" + sr.getName()+">>");
Attributes attrs = sr.getAttributes();
//System.out.println(sr.getName().matches("/^[0-9]/"));
System.out.println(attrs.get("cn").get());
System.out.println(attrs.get("mail").get());
isFound="1";
}
if ( isFound=="1") {
System.out.println("User found in Active Directory!");
} else {
System.out.println("Opps ! User not found in Active Directory!");
}
answer.close();
}catch(PartialResultException e) {
System.out.println("catch 2");
e.printStackTrace();
}
// Close the context when we're done
ctx.close();
} catch (Exception e) {
System.out.println("catch 1");
e.printStackTrace();
}
}
public LDAPQuery() {
// Don't think I'm doing anything here
}
}
OK, got it.
Any particular reason why you are utilizing an Agent as opposed to using a true bean? Calling an agent everytime someone opens the name picker in my opinion is far from being effective.
Apart from that I don't see a way how the results from your agent could directly be passed into the name picker.
Third: looking at your ldap filter I'm sure that your code will return hundreds or even thousands of names. Using a standard ExtLib NamePicker is no fun for your users, believe me: the list of names displayed per dialog page is way too limited. But that may be a different story.
Sticking to the namePicker approach there are several ways how you could achieve what you appear to accomplish:
refactor your java agent into a javaBean then feed the result to the control
consider going for a directory syncing tool like IBM TDI; thus your AD data can be pushed into a Domino directory of your choice, and then from within your application you can utilize standard name lookup features

Is Tyrus nessary to implement Java WebSocket authentication?

Although there's very similar post, it is unanswered.
My JavaFX app with WebSocket will
send user id、password to server
keep the session to let user do something like personal data management.
Learning from
Oracle WebSocket、
Tyrus 8.14 Client HTTP Authentication
I have:
#ClientEndPoint
public class loginEndPoint {
final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();
public static void main(String [] args) {
AuthConfig authConfig = AuthConfig.Builder.create().disableBasicAuth().build();
Credentials credentials = new Credentials("ws_user", "password");
client.getProperties().put(ClientProperties.AUTH_CONFIG, authConfig);
client.getProperties().put(ClientProperties.CREDENTIALS, credentials);
client.connectToServer(new Endpoint() {
#Override
public void onOpen(Session session, EndpointConfig config) {
try {
session.addMessageHandler((MessageHandler.Whole<String>) (String message) -> {
System.out.println("Received message: "+message);
messageLatch.countDown();
});
//let user do some data management
} catch (IOException e) {
System.out.println("Connect Fail.");
}
}
}, cec, new URI("ws://localhost/myApp/login"));
}
}
Is these code right to do the authentication? And where could I do the server side authentication on #ServerEndPoint?
#ServerEndpoint
public class loginServerEndPoint {
}
Thanks for help.
No, it is not necessary to use Tyrus as a server implementation.
On the server-side you should secure WebSocket in exactly the same way as you secure servlet or jsp in your servlet container, which can be slightly different from container to container (mapping users to roles).
Look at authentication example
Note that this example shows up how to make authenticated WebSocket request handshake with BASIC auth scheme, but your client code disables it explicitly, so probably you want to use DIGEST scheme.

email address on GAE

I have an application on google app engine like abc.appspot.com can I have an email address to send/receive emails like admin#abc.appspot.com kindly help me.
Edit
here is my SendMail class
public class SendMail {
private static String fromAddress = "abc#gmail.com";
private static Logger log = Logger.getLogger(SendMail.class.getCanonicalName());
// Send the Mail
public void send(String toAddress, String subject, String msgBody)
throws IOException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(fromAddress));
InternetAddress to = new InternetAddress(toAddress);
msg.addRecipient(Message.RecipientType.TO, to);
msg.setSubject(subject);
msg.setText(msgBody);
Transport.send(msg, new InternetAddress[] { to });
} catch (AddressException addressException) {
log.log(Level.SEVERE, "Address Exception , mail could not be sent", addressException);
} catch (MessagingException messageException) {
log.log(Level.SEVERE, "Messaging Exception , mail could not be sent", messageException);
}
}
}
So it sends an email regarding abc#gmail.com but I want that it should send from email#abc.appspot.com.
You can only receive emails in the form of #abc.appspotmail.com. AFAIK there is no way to have #abc.appspot.com as receiving address.
If you wan to receive emails from your custom domain, e.g. #abc.com, than the only way is to have external email service forward emails to your #abc.appspotmail.com. Most domain registrars offer free limited email service with forwarding (we use GoDaddy and get limited forwarding free).
Yes you can: https://developers.google.com/appengine/docs/java/mail/usingjavamail#Senders_and_Recipients

Exception occurred while reading mails from exchange server 2010 using imap

I am trying to read the mails from the exchange server 2010 , however sometimes the connection got established , but remaining times program gives below exception:
javax.mail.AuthenticationFailedException: LOGIN failed
The code is working fine with the exchange server 2007 . But from the time mailbox has been migrated to 2010, the program is behaving in this fashion only.
I have also tried with several options available on net, but nothing is working. I am using javamail-1.4.4 API version . Here is the piece of code through which I am just trying to connect to the mailbox .
public class ReadMail {
static Store store=null;
static String host="";
static String username="";
static String password="";
public static void main(String[] arg) throws Exception{
try{
Session session;
username = "username";
password = "password";
host = "hostname";
Properties props = System.getProperties();
props.setProperty("mail.smtp.auth","true");
session = Session.getInstance(props,
new ExchangeAuthenticator(username, password));
Store st = session.getStore("imaps");
st.connect(host,username, password);
System.out.println("Connected");
}
catch (Exception e){
e.printStackTrace(System.out);
}
}
}
public class ExchangeAuthenticator extends Authenticator {
String user;
String pw;
public ExchangeAuthenticator (String username, String password)
{
super();
this.user = username;
this.pw = password;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
}
I also face same problem in my code i set two properties in my code
disable plain test and enable NTLM
props.setProperty("mail.imap.auth.plain.disable","true");
props.setProperty("mail.imap.starttls.enable", "true");
now my code able to connect with exchange server
read it
https://forums.oracle.com/forums/thread.jspa?threadID=1587688
Perhaps the configuration of the server has changed and it's no longer accepting your credentials, or no longer supporting any of the login methods that JavaMail supports.
Turn on session debugging and examine the protocol trace. It should provide some clues as to why it's failing.
You might also want to upgrade to JavaMail 1.4.5, which has built-in support for NTLM authentication, which you might need.
Even though your credentials are OK, the new server might not accept your login method. For instance, the new server might not allow "Plain" authentication.
The debugging info should show which authentication methods are accepted.

Sending email using Javamail

I'm trying to send a mail using the GoDaddy email host I have registered couple of days ago using Java mail api, however it turns out that its not that easy to implement,
and I am getting, this error:
Could not connect to SMTP host: smtpout.asia.secureserver.net, port: 80, response: -1
I have tried ports 3535, 465, 587, 25 but still get the same error. The same code below has been tested to work with sending out email using Gmail, with the addition of this code (which I have omitted in this case):
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
MailSender.java:
public class MailSender {
private static String HOST = "smtpout.asia.secureserver.net";
private static String PORT = "80";
public static void sendMail(final Mail mail) throws MailException {
EmailValidator validtor = new EmailValidator();
if (validtor.validate(mail.getReceipient())) {
Properties props = new Properties();
props.put("mail.smtp.host", HOST);
props.put("mail.smtp.socketFactory.port", PORT);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", PORT);
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mail.getUsername(),mail.getPassword());
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(mail.getSender()));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(mail.getReceipient()));
message.setSubject(mail.getSubject());
message.setText(mail.getBody());
Transport.send(message);
System.out.println("OK");
} catch (MessagingException e) {
throw new MailException(e.getMessage());
}
} else {
throw new MailException("Email address not valid.");
}
}
}
The Mail parameter in this class holds all other mail information, the username/password, sender and recipient email address string, which is tested to work with email clients like Outlook & Thunderbird.
Port 80 is used for HTTP.
Change it to 465 or 587.
(Consult the GoDaddy documentation for the correct port)
Apparently, the problem was not with Java mail api, but was with GoDaddy server, I have consulted their tech support and work fine now.

Resources