Send javamail using Office365 - smtp

I'm having trouble configuring the SMTP settings for sending mail using javax.mail (1.4.4) through Office365, so I thought I'd post the properties here for others.

Use Office365 smtp details as below:
private static Properties props;
private static Session session;
static {
props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.host", "m.outlook.com");
props.put("mail.smtp.auth", "true");
session = Session.getInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("office365 email address",
"office365 password");
}
});
}

And with spring-boot, you simply need to add this to your application.properties:
spring.mail.host = smtp.office365.com
spring.mail.username = mathieu.pousse#headquarter.com
spring.mail.password = s3cr3t
spring.mail.port = 587
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.starttls.enable = true

A working code example:
Email email = new SimpleEmail();
email.setHostName("smtp.office365.com");
email.setSmtpPort(587);
email.setAuthenticator(new DefaultAuthenticator("a#b.com", "****"));
email.setStartTLSEnabled(true);
try {
email.setFrom("a#b.com");
email.setSubject("Job Failure");
email.setDebug(true);
email.setMsg("This is a test mail ... :-)" );
email.addTo("a#y.com");
email.send();
} catch (EmailException e) {
e.printStackTrace();
}

The only error that I am noticing in your code is the incorrect Host
javaMailProperties.setProperty("mail.smtp.from", "abc#c.com");
javaMailProperties.setProperty("mail.smtp.user", "abc#c.com");
javaMailProperties.setProperty("mail.smtp.password","Password");
javaMailProperties.setProperty("mail.smtp.host", "smtp.office365.com");
javaMailProperties.setProperty("mail.smtp.port", "587");
javaMailProperties.setProperty("mail.smtp.auth", "true");
javaMailProperties.setProperty("mail.smtp.starttls.enable", "true");
Change the host you will be all good.

Related

Javamail SMTPSenderFailedException 553

This code was working fine for months but has suddenly stopped working without any change in the code. The exception stack trace has:
com.sun.mail.smtp.SMTPSenderFailedException: 553 5.1.2 The address specified is not a valid RFC-5321 address. tj2sm1495299pab.4 - gsmtp
My code, which was working earlier:
final String username = uName;
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.debug", "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("<from email id>"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("<to email address>"));
message.setSubject("<subject>");
message.setContent(finalMessage, "text/html");
Transport.send(message);
} catch (MessagingException | UnsupportedEncodingException e) {
e.printStackTrace();
logger.error("Emailing error: "+e.getMessage());
}
This stopped working today.
What did it for me was changing the username-field content from "username" to "username#gmail.com".
change the "from email id" for the complete email adress
Google has change the last week the validation from standar RFC 5321 that covers the field "FROM"

HttpAsyncClient isn't making request if setConnectionManagerShared is set to true

For some reason HttpAsyncClient isn't making request if setConnectionManagerShared is set to true. I found this bug but couldn't figure out what I'm missing.
Here is how I create new client
def apply(proxy: Option[HttpHost], cookieStore: Option[CookieStore]) = {
val builder = HttpAsyncClients.custom.
setConnectionManager(connManager).
setConnectionManagerShared(true).
setDefaultCredentialsProvider(credentialsProvider).
setDefaultRequestConfig(defaultRequestConfig).
setSSLStrategy(sslStrategy)
proxy.map(builder.setProxy)
builder.setDefaultCookieStore(cookieStore.getOrElse(new BasicCookieStore)) // Use custom cookie store if necessary.
// Create an HttpClient with the given custom dependencies and configuration.
val client: HttpAsyncClient = new HttpAsyncClient(builder.build)
client
}
Full class is located is here.
What should I change ?
DefaultConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
CloseableHttpAsyncClient client1 = HttpAsyncClients.custom()
.setConnectionManager(cm)
.build();
CloseableHttpAsyncClient client2 = HttpAsyncClients.custom()
.setConnectionManager(cm)
.setConnectionManagerShared(true)
.build();
client1.start();
client2.start();
final CountDownLatch latch = new CountDownLatch(2);
FutureCallback callback = new FutureCallback<HttpResponse>() {
#Override
public void completed(HttpResponse result) {
latch.countDown();
System.out.println(result.getStatusLine());
}
#Override
public void failed(Exception ex) {
latch.countDown();
System.out.println(ex.getMessage());
}
#Override
public void cancelled() {
latch.countDown();
}
};
client1.execute(new HttpGet("http://httpbin.org/get"), callback);
client2.execute(new HttpGet("http://httpbin.org/get"), callback);
latch.await();
// I am aware this is sloppy
client1.close();
client2.close();

How to solve could not convert socket to TLS

this is my code mention in that box.so please check this code and give me right answer.this code is totally run in my system and run successfully and show build successful but message does not send in mail ids.so please help me.
Thanks in advance
this is my code.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class Main1
{
String d_email = "xyz#ibm.com",
d_password = "*******",
d_host = "blr-outlook.ibm.com",
d_port = "25",
m_to = "xyz#ibm.com",
m_subject = "Testing",
m_text = "Hey, this is the testing email using blr-outlook.ibm.com";
public static void main(String[] args)
{
String[] to={"xyz#ibm.com"};
String[] cc={"xyz#ibm.com"};
String[] bcc={"xyz#ibm.com"};
//This is for google
Main1.sendMail("xyz#ibm.com", "password", "blr-outlook.ibm.com",
"25", "true", "true",
true, "javax.net.ssl.SSLSocketFactory", "false",
to, cc, bcc,
"hi baba don't send virus mails..",
"This is my style...of reply..If u send virus mails..");
}
public synchronized static boolean sendMail(
String userName, String passWord, String host,
String port, String starttls, String auth,
boolean debug, String socketFactoryClass, String fallback,
String[] to, String[] cc, String[] bcc,
String subject, String text)
{
Properties props = new Properties();
//Properties props=System.getProperties();
props.put("mail.smtp.user", userName);
props.put("mail.smtp.host", host);
if(!"".equals(port)) {
props.put("mail.smtp.port", port);
}
if(!"".equals(starttls)) {
props.put("mail.smtp.starttls.enable",starttls);
}
props.put("mail.smtp.auth", auth);
if(debug) {
props.put("mail.smtp.debug", "true");
} else {
props.put("mail.smtp.debug", "false");
}
if(!"".equals(port)) {
props.put("mail.smtp.socketFactory.port", port);
}
if(!"".equals(socketFactoryClass)) {
props.put("mail.smtp.socketFactory.class",socketFactoryClass);
}
if(!"".equals(fallback)) {
props.put("mail.smtp.socketFactory.fallback", fallback);
}
try
{
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
msg.setText(text);
msg.setSubject(subject);
msg.setFrom(new InternetAddress("blr-outlook.ibm.com"));
for(int i=0;i<to.length;i++) {
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(to[i]));
}
for(int i=0;i<cc.length;i++) {
msg.addRecipient(Message.RecipientType.CC,
new InternetAddress(cc[i]));
}
for(int i=0;i<bcc.length;i++) {
msg.addRecipient(Message.RecipientType.BCC,
new InternetAddress(bcc[i]));
}
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, userName, passWord);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return true;
}
catch (Exception mex)
{
return false;
}
}
}
There are so many examples available in the net...even tutorialspoint have well explained examples....check it out here.....
http://www.tutorialspoint.com/javamail_api/javamail_api_overview.htm
i have used java mail api for mailing purposes and it works good enough.....i am away from home so i can't share the code with you now....
Edit:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMailTLS {
public static void main(String[] args) {
final String username = "username#gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
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("from-email#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email#gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
try this....authentication is not mandatory....and if you are using any kinda app you need to change your gmail account setting to allow access for less secured apps....

Send Email using gmail SMTP throwing AuthenticationFailedException

I am sending mail using smtp from my web site to gmail.its work well localy. But did't work in remote server
i am previously using this code:
public boolean sendMail(String subject, String bodyContent,String emailAddress){
boolean isMailsent=false;
final String SMTP_HOST= getText("email.smtp.host");
final String SOCKET_FACTORY_PORT= getText("email.socket.factory.port");
final String SMTP=getText("email.smtp.port");
final String MAIL_USER_EMAIL_ADDRESS=getText("email.username");
final String MAIL_USER_PASSWORD= getText("email.password");
final String EMAIL_FROMNAME= getText("email.fromname");
try{
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.socketFactory.port",SOCKET_FACTORY_PORT);
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", SMTP);
Authenticator auth = new SMTPAuthenticator(MAIL_USER_EMAIL_ADDRESS, MAIL_USER_PASSWORD);
Session session = Session.getInstance(props, auth);
Message message = new MimeMessage(session);
InternetAddress from = new InternetAddress(MAIL_USER_EMAIL_ADDRESS,EMAIL_FROMNAME);
message.setFrom(from);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailAddress));
message.setSubject(subject);
message.setContent(bodyContent,"text/html" );
Transport.send(message);
isMailsent=true;
}catch(Exception e){
LOGGER.error(e);
}
return isMailsent;
}
how to fix it please give me best example
You need to provide the correct GMail credentials to authenticate.

how to send HTML email

I have to send HTML file via email but not as attachment.
Message simpleMessage = new MimeMessage(mailSession);
try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
Transport.send(simpleMessage);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It is sending email simply with text message.
I want to send HTML content which is stored in another file but not as attachment
Don't upcast your MimeMessage to Message:
MimeMessage simpleMessage = new MimeMessage(mailSession);
Then, when you want to set the message body, either call
simpleMessage.setText(text, "utf-8", "html");
or call
simpleMessage.setContent(text, "text/html; charset=utf-8");
If you'd rather use a charset other than utf-8, substitute it in the appropriate place.
JavaMail has an extra, useless layer of abstraction that often leaves you holding classes like Multipart, Message, and Address, which all have much less functionality than the real subclasses (MimeMultipart, MimeMessage, and InternetAddress) that are actually getting constructed...
Here is my sendEmail java program. It's good to use setContent method of Message class object.
message.setSubject(message_sub);
message.setContent(message_text, "text/html; charset=utf-8");
sendEmail.java
package employee;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
public class SendEmail {
public static void sendEmail(String message_text, String send_to,String message_sub ) throws UnsupportedEncodingException {
final String username = "hello#xyz.com";
final String password = "password";
Properties prop = new Properties();
prop.put("mail.smtp.host", "us2.smtp.mailhostbox.com"); //replace your host address.
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.starttls.enable", "true"); //TLS
Session session = Session.getInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("sender#xyz.com", "Name from which mail has to be sent"));
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse(send_to)
);
message.setSubject(message_sub);
message.setContent(message_text, "text/html; charset=utf-8");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}