Office365 JavaMail error - jakarta-mail

I have a Java class that works perfectly to send emails with a Gmail account. However, I've used the recomended SMTP settings, there is an error when I try to send an email with an Office365 account. The error returned is this:
exception
javax.servlet.ServletException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.office365.com, port: 587;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
Below is my code:
public class GmailBean {
public static final String SERVIDOR_SMTP = "smtp.office365.com";
public static final int PORTA_SERVIDOR_SMTP = 587;
private static final String CONTA_PADRAO = "xxx#xxx.com";
private static final String SENHA_CONTA_PADRAO = "xxx";
private String de;
private String para;
private String assunto;
private String mensagem;
public void enviarEmail() throws MessagingException {
FacesContext context = FacesContext.getCurrentInstance();
AutenticaUsuario autenticaUsuario = new AutenticaUsuario(GmailBean.CONTA_PADRAO, GmailBean.SENHA_CONTA_PADRAO);
Session session = Session.getInstance(this.configuracaoEmail(), autenticaUsuario);
// try{
Transport envio = null;
MimeMessage email = new MimeMessage(session);
email.setRecipient(Message.RecipientType.TO, new InternetAddress(this.para));
email.setFrom(new InternetAddress(this.de));
email.setSubject(this.assunto);
email.setContent(this.mensagem, "text/plain");
email.setSentDate(new Date());
envio = session.getTransport("smtp");
envio.connect(GmailBean.SERVIDOR_SMTP, GmailBean.CONTA_PADRAO, GmailBean.SENHA_CONTA_PADRAO);
email.saveChanges();
envio.sendMessage(email, email.getAllRecipients());
envio.close();
context.addMessage(null, new FacesMessage("Mensagem enviada com sucesso!"));
/* }
catch(AddressException ex)
{ Logger logger = Logger.getAnonymousLogger();
FacesMessage msg = new FacesMessage("Erro ao enviar mensagem "+ ex.getMessage());
logger.info("Erro ao enviar mensagem _____________"+ ex.getMessage());
}
catch(MessagingException ex)
{
Logger logger = Logger.getAnonymousLogger();
FacesMessage msg = new FacesMessage("Erro ao enviar mensagem "+ ex.getMessage());
logger.info("Erro ao enviar mensagem _____________"+ ex.getMessage());
}*/
}
public Properties configuracaoEmail() {
Properties config = new Properties();
config.put("mail.smtp.auth", "true");
config.put("mail.transport.protocol", "smtp");
config.put("mail.smtp.starttls.enabled", "true");
config.put("mail.smtp.host", SERVIDOR_SMTP);
config.put("mail.user", GmailBean.CONTA_PADRAO);
config.put("mail.smtp.port", PORTA_SERVIDOR_SMTP);
config.put("mail.smtp.socketFactory.port", PORTA_SERVIDOR_SMTP);
config.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
config.put("mail.smtp.socketFactory.fallback", "false");
return config;
}
// (Getters and setters... )
class AutenticaUsuario extends Authenticator {
private String usuario;
private String senha;
public AutenticaUsuario(String usuario, String senha) {
this.usuario = usuario;
this.senha = senha;
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(this.usuario, this.senha);
}
}

Fix all these common mistakes and it should work.
The JavaMail FAQ entry for outlook.com should work for Office365 as well by changing the host name.

Related

How to make BasicAuthentication in SolrJ - CloudSolrClient?

I am using Solr 7.5 Server and I had used External Zookeeper.When I browse using the Solr Admin UI It ask authentication to me.
For Java Client I had used the below Code
BasicAuthSolrClientCache bs = new BasicAuthSolrClientCache("solr", "SolrRocks");
CloudSolrClient solrCloudClient = bs.getCloudSolrClient(zkHost);
solrCloudClient.setDefaultCollection("sample");
SolrInputDocument doc = new SolrInputDocument();
doc.addField("cat", "book");
doc.addField("id", "book-1");
doc.addField("name", "The Legend of the Hobbit part 1");
solrCloudClient.add(doc);
solrCloudClient.commit();
solrCloudClient.close();
BasicAuthSolrClientCache.java
public class BasicAuthSolrClientCache extends SolrClientCache {
private static final Logger log =
LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final Map<String, SolrClient> solrClients = new HashMap<>();
private final String username;
private final String password;
public BasicAuthSolrClientCache(String username, String password) {
this.username = username;
this.password = password;
}
#Override
public synchronized CloudSolrClient getCloudSolrClient(String zkHost) {
CloudSolrClient client;
if (solrClients.containsKey(zkHost)) {
client = (CloudSolrClient) solrClients.get(zkHost);
} else {
client = new CloudSolrClient.Builder()
.withZkHost(zkHost)
.withHttpClient(getHttpClient())
.build();
client.connect();
solrClients.put(zkHost, client);
}
return client;
}
#Override
public synchronized HttpSolrClient getHttpSolrClient(String host) {
HttpSolrClient client;
if (solrClients.containsKey(host)) {
client = (HttpSolrClient) solrClients.get(host);
} else {
client = new HttpSolrClient.Builder(host)
.withHttpClient(getHttpClient())
.build();
solrClients.put(host, client);
}
return client;
}
#Override
public synchronized void close() {
for(Map.Entry<String, SolrClient> entry : solrClients.entrySet()) {
try {
entry.getValue().close();
} catch (IOException e) {
log.error("Error closing SolrClient for " + entry.getKey(), e);
}
}
solrClients.clear();
}
private HttpClient getHttpClient() {
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new
UsernamePasswordCredentials(this.username, this.password);
provider.setCredentials(AuthScope.ANY, credentials);
return
HttpClientBuilder.create().setDefaultCredentialsProvider(provider).
build();
}
}
But it give the exception like the below,
Exception in thread "main" org.apache.solr.client.solrj.impl.CloudSolrClient$RouteException: IOException occured when talking to server at: http://192.168.0.104:8983/solr/gettingstarted_shard2_replica1 at
How to authenticate SolrCloud using SolrJ
I found a easy way to do this.
You add a request interceptor like this so you do not have to worry about creating a properly configured HttpClient instance yourself. This will just add the interceptor to the default HttpClient that Solrj creates.
org.apache.solr.client.solrj.impl.HttpClientUtil.addRequestInterceptor(new SolrPreemptiveAuthInterceptor());
The RequestInterceptor looks like this:
public class SolrPreemptiveAuthInterceptor implements HttpRequestInterceptor {
final static Logger log = LoggerFactory.getLogger(SolrPreemptiveAuthInterceptor.class);
#Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
// If no auth scheme available yet, try to initialize it preemptively
if (authState.getAuthScheme() == null) {
log.info("No AuthState: set Basic Auth");
HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
Credentials creds = credsProvider.getCredentials(authScope);
if(creds == null){
log.info("No Basic Auth credentials: add them");
creds = getCredentials(authScope);
}
authState.update(new BasicScheme(), creds);
}
}
private Credentials getCredentials(AuthScope authScope) {
String user = "";
String password = "";
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(authScope, creds);
log.info("Creating Basic Auth credentials for user {}", user);
return credsProvider.getCredentials(authScope);
}
}
You can also use UpdateRequest for indexing requests to do a basic authentication via SolrJ:
UpdateRequest ur = new UpdateRequest();
ur.add(doc);
ur.setBasicAuthCredentials("YOU USER NAME", "USER PASSWORD");
ur.setCommitWithin(COMMIT_WITHIN_INTERVAL);
ur.process(cloudSolrClient);

Sending a Yahoo Email with JavaMail API

I am trying to send an email to a yahoo email account with this code.
However, I get this message:
javax.mail.MessagingException: Could not connect to SMTP host: winmo.smtp.mail.yahoo.com, port: 465, response: -1
I dont know what is wrong. I am new to java.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String to = "myemail#yahoo.com";
System.out.println("Type the subject of the email");
String subject = s.nextLine();
System.out.println("Type the content of the message");
String body = s.nextLine();
String from = "web#gmail.com";
String host = "winmo.smtp.mail.yahoo.com";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.port", "465");
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
System.out.println("sent");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}

How to send out an Email notification in selenium webdriver using java

How to send out an Email notification in selenium webdriver using java, whenever some scenario is failed/passed in between ??
Following code will allow you to send mail using JAVA. Create one function and call it after scenario of Pass/Fail in selenium webdriver code.
final String username = "YourEmail";
final String password = "YourPassword";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "mail.example.com");
props.put("mail.smtp.port", "25");
props.put("java.net.preferIPv4Stack", "true");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("YourEmail"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("Emailid to which you want to send Report"));
message.setSubject("Email Subject");
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("Body text);
//4) create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "File path if you want to attach in mail";//change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
//5) create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
//6) set the multiplart object to the message object
message.setContent(multipart );
Transport.send(message);
System.out.println("Mail Sent Successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
Note : Please change Host, Email details and port as per your Email system configuration.
Wrote a method in Utility class file and call it from condition where test case fails.
public static void sendEmail(string message, string testCaseName)
{
MailMessage mail = new MailMessage();
mail.To.Add("your-to-email-address-goes-here");
mail.From = new MailAddress("your-from-email-address-goes-here ");
mail.Subject = "your-mail-subject-goes-here";
mail.Body = "Test Case Name: " + testCaseName;
mail.Body += Environment.NewLine;
mail.Body += message;
SmtpClient smtp = new SmtpClient();
smtp.Host = "localhost";
smtp.Port = 25;
smtp.Send(mail);
}
You can call this method in your test case, when it should fail. User will be notified via email.
**use proper SMTP configuration
Here is my sample for sending out emails via javax.mail:
pom dependancy:
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>
1. STEP (model MailMessage) you need model class of mail message:
public class MailMessage {
private String from;
private List<String> to;
private List<String> cc;
private List<String> bcc;
private String subject;
private Date sendDate;
private String flags;
private String content;
private List<File> attachments;
public MailMessage() {
}
public MailMessage(String from, String to, String subject, String content)
List<String> listTo = new ArrayList<>();
List<String> listCC = new ArrayList<>();
List<String> listBCC = new ArrayList<>();
listTo.add(to);
new MailMessage(from, listTo, listCC, listBCC, subject, content);
}
public MailMessage(String from, String to, String cc, String subject, String content) {
List<String> listTo = new ArrayList<>();
List<String> listCC = new ArrayList<>();
List<String> listBCC = new ArrayList<>();
listTo.add(to);
listCC.add(cc);
new MailMessage(from, listTo, listCC, listBCC, subject, content);
}
public MailMessage(String from, List<String> to, List<String> cc, List<String> bcc, String subject, String content) {
setFrom(from);
setTo(to);
setCc(cc);
setBcc(bcc);
setSubject(subject);
setContent(content);
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public List<String> getTo() {
return to;
}
public void setTo(List<String> to) {
this.to = to;
}
public List<String> getCc() {
return cc;
}
public void setCc(List<String> cc) {
this.cc = cc;
}
public List<String> getBcc() {
return bcc;
}
public void setBcc(List<String> bcc) {
this.bcc = bcc;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public Date getSendDate() {
return sendDate;
}
public void setSendDate(Date sendDate) {
this.sendDate = sendDate;
}
public String getFlags() {
return flags;
}
public void setFlags(String flags) {
this.flags = flags;
}
public String getContent() {
return content;
}
public void setContent(String fieldMessage) {
this.content = fieldMessage;
}
public List<File> getAttachments() {
return attachments;
}
public void setAttachments(List<File> attachments) {
this.attachments = attachments;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("-------------------------------------\n");
sb.append("FROM: " + getFrom() + "\n");
sb.append("TO: " + getTo() + "\n");
sb.append("Subject: " + getSubject() + "\n");
sb.append("Send Date: " + getSendDate() + "\n");
sb.append("Flags: " + getFlags() + "\n");
sb.append("Messages: " + getContent() + "\n");
sb.append("-------------------------------------\n");
return sb.toString();
}
}
2. STEP (create message, populate model)
protected MailMessage createMessage(String to, String subject, String content) {
List<String> listTo = new ArrayList<>();
List<String> listCC = new ArrayList<>();
List<String> listBCC = new ArrayList<>();
listTo.add(to);
return createMessage(listTo, listCC, listBCC, subject, content);
}
protected MailMessage createMessage(List<String> to, List<String> cc, List<String> bcc, String subject, String content) {
MailMessage mailMessage = new MailMessage();
mailMessage.setFrom(getUsername());
mailMessage.setTo(to);
mailMessage.setCc(cc);
mailMessage.setBcc(bcc);
mailMessage.setSubject(subject);
mailMessage.setContent(content);
return mailMessage;
}
3. STEP method for sending message via model (MailMessage):
public boolean sendMessage(MailMessage mailMessage) {
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(getSession());
// Set From: header field of the header.
message.setFrom(new InternetAddress(mailMessage.getFrom()));
// Set To: header field of the header.
for (String fieldTo : mailMessage.getTo()) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(fieldTo));
}
for (String fieldCc : mailMessage.getCc()) {
message.addRecipient(Message.RecipientType.CC, new InternetAddress(fieldCc));
}
for (String fieldBcc : mailMessage.getBcc()) {
message.addRecipient(Message.RecipientType.BCC, new InternetAddress(fieldBcc));
}
// Set Subject: header field
message.setSubject(mailMessage.getSubject());
// Now set the actual message
message.setText(mailMessage.getContent());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(mailMessage.getContent(), "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (mailMessage.getAttachments() != null && mailMessage.getAttachments().size() > 0) {
for (File filePath : mailMessage.getAttachments()) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(filePath.getAbsolutePath());
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
// sets the multi-part as e-mail's content
message.setContent(multipart);
// Send message
Transport.send(message);
return true;
} catch (MessagingException mex) {
mex.printStackTrace();
return false;
}
}
Hope this would help,

sending mail using javamail getting authentication issue

When I tried to send mail using following code, I got authentication issues.
Here's my code:
public class NewSendMail {
String to = "********";
String subject = "subject";
String msg ="email text....";
final String from ="*******";
final String password ="******";
public NewSendMail(){
}
public boolean sendMymail(){
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.debug", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,password);
}
});
// Session session = Session.getDefaultInstance(props);
//session.setDebug(true);
Transport transport;
InternetAddress addressFrom = null;
try {
transport = session.getTransport();
addressFrom = new InternetAddress(from);
MimeMessage message = new MimeMessage(session);
message.setSender(addressFrom);
message.setSubject(subject);
message.setContent(msg, "text/plain");
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
transport.connect();
Transport.send(message);
transport.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
}
It is throwing a javax.mail.AuthenticationFailedException.
How can I fix the issue?
The following code may help you
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "username"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "password"; // GMail password
private static String RECIPIENT = "xxxxx#gmail.com";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "hi ....,!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.trust", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
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(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
This code worked for me, If it is not working for you, Check your jar files
I tell everyone who asks for JavaMail help the same things. (I wonder why they call it a FAQ?)
Fix these common mistakes.
Follow this example for Gmail.
Turn on session debugging to get more details of what's going wrong, and post the output if you still can't figure it out.
Either you're sending the wrong username or password, or the server is rejecting your login attempt for other reasons, perhaps because you haven't enabled less secure apps.

android app development-passing parameter to database

I am trying to connect my app to database on localhost server.I can connect to it ut the problem is how to pass the parameter from app to php script.for eg i want all names having age less than 10 so i will pass the parameter to php.below is my code for connecting to database.please provide good reference
/* */
enter code here
public class TestExternalDatabaseActivity extends Activity {
/** Called when the activity is first created. */
TextView resultView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.enableDefaults(); //STRICT MODE ENABLED
resultView = (TextView) findViewById(R.id.result);
getData();
}
public void getData(){
String result = "";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/tahseen0amin/php/getAllCustomers.php"); //YOUR PHP SCRIPT ADDRESS
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
resultView.setText("Couldnt connect to database");
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"Name : "+json.getString("FirstName")+" "+json.getString("LastName")+"\n"+
"Age : "+json.getInt("Age")+"\n"+
"Mobile Using : "+json.getString("Mobile")+"\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
}
}

Resources