How to send an email from Outlook via Java? - java

I am stuck behind a corporate firewall that won't let me send email via conventional means such as Java Mail API or Apache Commons Email, even to other people inside the organization(which is all I want anyways). But my Outlook 2010 obviously can send these emails. I was wondering if there is a way to automate Outlook 2010 via Java code so that Outlook can send the emails ? I know stuff like "mailto" can be used pop-up the default Outlook send dialog with pre-populated info, but I am looking for a way to have the send operation happen behind the scenes. Thanks for any info.

You can send emails through outlook with javamail use the configurations described on Outlook's official site.
Here is small demo code
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public static void main(String[] args) {
final String username = "your email"; // like yourname#outlook.com
final String password = "*********"; // password here
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp-mail.outlook.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(true);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("receiver mail")); // like inzi769#gmail.com
message.setSubject("Test");
message.setText("HI you have done sending mail with outlook");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
.
Note: I tested this with Javamail API 1.5.6

I don't think there's any way to do what you want using Outlook.
Presumably your mail server is also behind the corporate firewall. If you're using Outlook for your client, you're probably using Exchange for your server. Exchange can be configured to support the standard SMTP protocol for sending mail, which would allow use of JavaMail. If you can't configure your Exchange server to support SMTP, you still might be able to use Exchange Web Services. If that doesn't work, you might need to use one of the JavaMail Third Party Products that supports the Microsoft proprietary mail protocol.

Process p = Runtime.getRuntime().exec("cmd /C start outlook ");

Related

Send mail using Gmail from Java without turning on less secure app

I am attempting to send mail using Java to a Gmail account, code below. I appear to be doing everything correctly, however I receive an authentication failure. Google wants me to turn on the "less secure app" feature to enable transmission.
Is there a way to code in such a way that Gmail is happy with Java and will not throw the "turn on less secure apps" fault?
Error:
javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=...U
534-5.7.14 FigguJaZwDtp...
534-5.7.14 ...o> Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/answer/... - gsmtp
Code:
String hostSmtpUser = "myemail#gmail.com";
String host = "smtp.gmail.com";
String hostPort = "587";
String hostSmtpPassword = "thepassword";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.user", hostSmtpUser);
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.port", hostPort);
properties.setProperty("mail.smtp.auth", "true");
Session oSession;
if (true == ToolsCommon.isEmpty(hostSmtpUser))
oSession = Session.getInstance(properties);
else
oSession = Session.getInstance(properties, new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(hostSmtpUser, hostSmtpPassword);
}
});
// Compose the message
try
{
MimeMessage message = new MimeMessage(oSession);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(Subject);
message.setText(Body);
// Send message
Transport.send(message);
}
catch (MessagingException ex)
{
// Log the error.
ToolsLog.logError(TypeLog.ui, ex);
}
I already did research, so the code to my knowledge is not the problem, just do not see a workaround for the less secure apps message.
References:
Ref 1
Ref 2
Ref 3
Ref 4
By default, GMail doesn't allow password-based authentication -- that's why you'd have to allow "less-secure apps" to use your program as-is.
Instead, you can use OAuth 2.0 to avoid using a password directly. That method is considered secure by Google and won't require changing any account settings.
Less secure apps (https://myaccount.google.com/u/0/lesssecureapps) options is disabled and we can longer use it to send mail.
But there is a better option provided by google - apppasswords
https://myaccount.google.com/u/0/apppasswords
Use 16 digit code provided by google instead of password and that should be it.
Note: 2-factor authentication needed to be enabled before using appspasswords.

javax.mail.AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful

I am sending e email using an SMTP error . I am getting Authentication unsuccessful. The username and password are correct. Am I doing something wrong.
The error logs are
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailSender{
public static void main(String args[]) {
String to = "ssss#xxx.om"; // sender email
String from = "dddd#xxx.com"; // receiver email
String host = "dkdkdd.xxx.com"; // mail server host
String login="dkkdkd";
String pass="dkkdkd";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.user", login);
properties.setProperty("mail.smtp.password", pass);
properties.setProperty("mail.smtps.ssl.enable", "true");
// properties.setProperty("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties); // default session
try {
MimeMessage message = new MimeMessage(session); // email message
message.setFrom(new InternetAddress(from)); // setting header fields
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Test Mail from Java Program"); // subject line
// actual mail body
message.setText("You can send mail from Java program by using");
// Send message
Transport transport = session.getTransport("smtp");
transport.connect(host, login, pass);
Transport.send(message);
System.out.println("Email Sent successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
The error is
DEBUG SMTP: AUTH NTLM failed
Exception in thread "main" javax.mail.AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:826)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:761)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
Had the same issue. It's an MS Exchange error that you receive. You are probably not allowed to use your email to send an email via a relay. The administrator of the Exchange server needs to give the rights to do that.
It has nothing to do with a configuration problem on the Java side.
It looks like the problem in how you do the session part...
try doing this:
private Properties emailPorperties;
...
...
emailPorperties = new Properties();
emailPorperties.put("mail.smtp.host", "your host");
emailPorperties.put("mail.smtp.socketFactory.port", "your port");
emailPorperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
emailPorperties.put("mail.smtp.auth", "true");
emailPorperties.put("mail.smtp.port", "your port");
emailPorperties.put("mail.smtp.ssl.enable", "true");
emailSession = Session.getInstance(emailPorperties, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
System.out.println("Authenticating");
return new PasswordAuthentication(USER_NAME, PASSWORD);
}
});
Hello i've got the same issue in the past.
So to solve it i have to connect on the webmail of my outlook or exchage and i noticed that these connexions were stopped by the server so inside i confirm that these transactions was mine.
So u have also to do it usually every 2 month in my case.
The problem is not in the code. The problem occurs because something is wrong with the configuration of the mailboxes I believe.
Same issue resolve by enabling IMAP of the sender email account in Exchange Control Panel (ECP) of outlook mail admin.
Go to your Microsoft admin account and turn off the multi-factor authentication.
By default it is enabled. Once you disable the multi-factor authentication then it works fine for me.
I had a similar issue and in my case, the issue was 'outlook password got expired'.
As I had it logged in default I did not have any issue while logging in to my mail.
I tried logging in to incognito mode and see if my logging asked for an additional layer for logging like multi-factor auth, And when logged in from the incognito tab it asked to change the password with a popup stating 'password got expired'.
I then updated the new password and it started to work fine !!

Send Java email without authentication (no such provider exception: smtp)

The code I am currently using is as follows:
String to = "....#gmail.com";
String from = ".....#gmail.com";
String host = "127.0.0.1";
Properties properties = System.getProperties();
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("This is the Subject Line!");
message.setText("This is actual message");
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
If I paste the above code in my Java servlet and run it, the following exception gets thrown:
javax.mail.NoSuchProviderException: smtp
I have also tried following the solutions outlined in these resources but to no avail: link1 link2 link3 link4.
It would help if you included the the full stacktrace for the javax.mail.NoSuchProviderException and JavaMail debug output. Because you are running this in a servlet container you could be running into Bug 6668 -skip unusable Store and Transport classes. Change your call to Transport.set to the following:
final ClassLoader ccl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(Session.class.getClassLoader());
try {
Transport.send(message);
} finally {
Thread.currentThread().setContextClassLoader(ccl);
}
That code will isolate which transport class the code is allowed to see. That will rule out that bug in your code.
NoSuchProviderException means something is messed up in your JavaMail API configuration. Where and how have you installed the JavaMail jar file?
Also, in case it's not clear from the other responses, the only way you're going to be able to send mail without authentication is if you're running your own mail server. You can't do it with general purpose online e-mail services (e.g. Gmail).
First of all, if you wanna use gmail to send emails from your program you need to define stmp host as gmail. Your current host "127.0.0.1" is localhost meaning your own computer? Do you have mail server running on your computer?
Here you can see some tutorial how to send an email using gmail: http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
If you're afraid to pass your normal gmail account details then create some kind of test email like kselvatest or something.
You are missing pretty much those:
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");
So basicly all you need to add is:
1.login and password so JavaMail can use some gmail account
2.declare which mail server you wanna use
change String host = "127.0.0.1"; to String host = "smtp.gmail.com";
3.set mail port
For this code you should get javax.mail.MessagingException: Could not connect to SMTP host: 127.0.0.1, port: 25; exception
But I suspect you have a jre issue. May be smtp implementation has a problem. Why don't you download java mail implementation from http://www.oracle.com/technetwork/java/javamail/index-138643.html and add it to your project class path and try?

send mail through java : multiple sender with different mail id

I want to send one mail to specified recipient but my sender can have different mail account like outlook or ymail or gmail.
Is it possible to send an email from different email id to same recipient? I'm using this code :
try
{final String from=request.getParameter("from");String smtpServ="",port="";final String pass=request.getParameter("pass");String to=request.getParameter("to");String subject=request.getParameter("subject");String body=request.getParameter("msg");if(from.contains("#gmail.com")){smtpServ="smtp.gmail.com";port="465";}else if(from.contains("#outlook.com") || from.contains("#hotmail.com")){smtpServ="smtp.live.com";port="587";}else if(from.contains("#ymail.com") || from.contains("#yahoo.com") || from.contains("#rocketmail.com") || from.contains("#yahoo.in")){smtpServ="smtp.mail.yahoo.com";port="465";}Properties props = System.getProperties();
// -- Attaching to default Session, or we could start a new one --
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host",smtpServ);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", port);
Session session1 = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,pass);
}
});Message message = new MimeMessage(session1);message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
message.setSubject(subject);
message.setText(body);
// -- Set some other header information --
message.setHeader("MyMail", "Java Mail Test");
message.setSentDate(new Date());Transport.send(message);System.out.println("Message sent to"+to+" OK."); }
catch (Exception ex)
{ ex.printStackTrace();System.out.println("Exception "+ex); }
Sending mails via Java (using Java Mail API) requires you to setup an SMTP host that would send your email to the recipient after proper log-in validation. I've used Java Mail with Gmail IDs and Gmail as SMTP host server. Some e-mail service providers do not allow sending emails from outside of their own web-services (making them incompatible with Java Mail).
But, in order to support multiple senders, you'll need to do the following:
Change the SMTP server to your correct host as per the email ID in use.
Run the Authenticator, with the new e-mail address and password, every time the sender ID is changed.
Then send your message.
My suggestion would be to store these sender email IDs and passwords (and SMTP hosts) when the program is initially run and then iterate the above steps with required changes, for each email id and password pair.
The Caveat:
In my opinion it's best to stick with a single sender else, multiple messages with similar content, by varied sender addresses, may be marked down as Spam by the recipients email service provider.
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
replace this thing with,
message.setRecipients(Message.RecipientType.TO, Address[] addresses);
[N.B.- addresses are ur desired IDs.]

How do I configure a mail server for use with JavaMail?

I'm trying to work with the below code:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*; // important
import javax.mail.event.*; // important
import java.net.*;
import java.util.*;
public class servletmail extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
response.setContentType("text/html");
try {
Properties props=new Properties();
props.put("mail.smtp.host","localhost"); // 'localhost' for testing
Session session1 = Session.getDefaultInstance(props,null);
String s1 = request.getParameter("text1"); //sender (from)
String s2 = request.getParameter("text2");
String s3 = request.getParameter("text3");
String s4 = request.getParameter("area1");
Message message =new MimeMessage(session1);
message.setFrom(new InternetAddress(s1));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(s2,false));
message.setSubject(s3);
message.setText(s4);
Transport.send(message);
out.println("mail has been sent");
} catch(Exception ex) {
System.out.println("ERROR....."+ex);
}
}
}
I'm using mail.jar and activation.jar. But I can't understand how I should configure it with a mail server. Which mail server should I use? Will I be able to send an email using above code? What are the requirements a mail server? How should I configure it?
To start, you need a SMTP server. It's required to be able to send emails. The same way as you need a HTTP server to be able to serve a website. You apparently already have a HTTP server (with a servletcontainer), but you don't have a SMTP server configured yet.
You can make use of the SMTP server associated with your own existing email account, such as the one from your ISP or public mailboxes like Gmail, Yahoo, etc. You can find SMTP connection details in their documentation. You usually just need to know the hostname and the port number. The username/password are just the same as those of your email account.
The hostname and port number should then be set as SMTP properties for JavaMail:
Properties properties = new Properties();
properties.put("mail.transport.protocol", "smtp");
properties.put("mail.smtp.host", "smtp.example.com"); // smtp.gmail.com?
properties.put("mail.smtp.port", "25");
The username/password should be used in a Authenticator as follows:
properties.put("mail.smtp.auth", "true");
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("yourusername", "yourpassword");
}
};
Then you can get the mail session as follows:
Session session = Session.getDefaultInstance(properties, authenticator);
With the account of your ISP or public mailboxes, you're however restricted to using your own address in the From field of the email and usually also in the amount of emails you're allowed to send at certain intervals. If you'd like to get around this, then you need to install your own SMTP server, for example Apache James, which is Java based, or Microsoft Exchange and so on.
After all, I suggest you to get yourself through a JavaMail tutorial so that you get a better understanding.

Categories