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

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.

Related

How to send an email from Outlook via 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 ");

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 !!

Sending Email using java timeout exception

I am trying to send email to gmail using java. I am using this code.
final String username = "xyz#gmail.com";
final String 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);
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("xyz#gmail.com"));
message.setRecipient(Message.RecipientType.TO,newInternetAddress("abcdef#gmail.com"));
message.setSubject("First email to using java");
message.setContent("<h:body style =background-color:white> This is a test mail sent using java" + "</body>","text/html; charset=utf-8");
Transport.send(message);
System.out.println("Message Sent");
But When i run the above code it shows follwoing error:
Exception in thread "main" com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 587; timeout -1;
I have an Internet connection which uses proxy server and requires authentication. Is this error because of Proxy or there is some problem in my code. Please tell me how to resolve it.
JavaMail can't use a web proxy server directly, although it can use a SOCKS proxy server. If you only have a web proxy server, programs like Corkscrew can help.
You can setup SOCKS proxy server in JavaMail with like this:
Properties p = System.getProperties();
p.setProperty("proxySet","true");
p.setProperty("socksProxyHost","192.168.1.1");
p.setProperty("socksProxyPort","1234");
Yes, it's because of your proxy server.
How do I configure JavaMail to work through my proxy server?
the above link expired: check this link
http://www.oracle.com/technetwork/java/faq-135477.html#proxy

mail in java with desired "from" name

Does any one know how to send an email with the desired "from" name in Java ?
I have a code which sends the mail through gmail. Using the smtp settings of gmail, I am able to do that. But, using the same smtp settings, can I send an email from a non-existing mail ID ?
For example:
I have a code which sends an email from the existing username (say abc#gmail.com) and the receiver gets the email from abc#gmail.com . But , what I want is , can we send a mail from something like "a#def.com" ? So that, the user receives the mail from "a#def.com" ?
Is that possible ?
While the API may allow you to do that, your difficulty is going to be with the SMTP server's configuration. No sane SMTP server would allow you to control the "from" email address of email messages sent through that SMTP server - that's the first step of making your SMTP server an easy gateway for spammers. Proper SMTP servers (Google's included) will set the "from" email address to be identical to the one you logged in with.
You can set it explicitly. But again it depends on the SMTP server that accepts the FROM address. To my knowledge most of the SMTPs are configured to block the sender email ids that do not belong to its domain. If at all they are not configured so, the receiving mail clients may filter the message for not identifying the sender email id from the receiving server and set it as SPAM. This would also cause the SMTP domain being blocked by many other receiving domains.
Hence it is not suggested to be followed.
You need mail.jar and activation.jar. In my case i implemented using below method
import java.util.HashMap;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.internet.MimeMessage;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.Transport;
class ABC{
......
private void sendSimpleEmail(String to,String subject,String cc,String bcc,String message,HashMap mailMap)
{
String smtpHost=mailMap.get("mailhost").toString();
String smtpPort=mailMap.get("mailport").toString();
String authrequired=mailMap.get("auth").toString();
String from=mailMap.get("mailsendfrom").toString();
String SSLCheck=mailMap.get("sslconfig").toString();
/* For Authentication */
String password=mailMap.get("mailpwd").toString();
String fromUsername=mailMap.get("mailusername").toString();
/* For Authentication Ends*/
Properties props = new Properties();
props.put("mail.smtp.auth", authrequired);
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", smtpPort);
Session session=Session.getDefaultInstance(props);
Message simpleMessage = new MimeMessage(session);
try {
InternetAddress fromAddress = new InternetAddress(from);
InternetAddress toAddress = new InternetAddress(to);
} catch (AddressException e) {
//Exception
}
try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(message);
Transport.send(simpleMessage);
} catch (MessagingException e) {
// TODO Auto-generated catch block
}
}
.......
}

Using JavaMail with TLS

I found several other questions on SO regarding the JavaMail API and sending mail through an SMTP server, but none of them discussed using TLS security. I'm trying to use JavaMail to send status updates to myself through my work SMTP mail server, but it requires TLS, and I can't find any examples online of how to use JavaMail to access an SMTP server that requires TLS encryption. Can anyone help with this?
We actually have some notification code in our product that uses TLS to send mail if it is available.
You will need to set the Java Mail properties. You only need the TLS one but you might need SSL if your SMTP server uses SSL.
Properties props = new Properties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true"); // If you need to authenticate
// Use the following if you need SSL
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
You can then either pass this to a JavaMail Session or any other session instantiator like Session.getDefaultInstance(props).
Good post, the line
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
is mandatory if the SMTP server uses SSL Authentication, like the GMail SMTP server does. However if the server uses Plaintext Authentication over TLS, it should not be present, because Java Mail will complain about the initial connection being plaintext.
Also make sure you are using the latest version of Java Mail. Recently I used some old Java Mail jars from a previous project and could not make the code work, because the login process was failing. After I have upgraded to the latest version of Java Mail, the reason of the error became clear: it was a javax.net.ssl.SSLHandshakeException, which was not thrown up in the old version of the lib.
The settings from the example above didn't work for the server I was using (authsmtp.com). I kept on getting this error:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
I removed the mail.smtp.socketFactory settings and everything worked. The final settings were this (SMTP auth was not used and I set the port elsewhere):
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.starttls.enable", "true");
Just use the following code. It is really useful to send email via Java, and it works:
import java.util.*;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.*;
import javax.mail.Provider;
import javax.mail.internet.*;
public class Main {
public static void main(String[] args) {
final String username="your#gmail.com";
final String password="password";
Properties prop=new Properties();
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
String body="Dear Renish Khunt Welcome";
String htmlBody = "<strong>This is an HTML Message</strong>";
String textBody = "This is a Text Message.";
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your#gmail.com"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("receiver#gmail.com"));
message.setSubject("Testing Subject");
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
message.setText(htmlBody);
message.setContent(textBody, "text/html");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
I just spent quite a bit of time figuring out how to use JavaMail to send emails with gmail or office365. I couldn't find the answer in the faq, but was helped a bit by the javadoc.
If you forget props.put("mail.smtp.starttls.enable","true") you get com.sun.mail.smtp.SMTPSendFailedException: 451 5.7.3 STARTTLS is required to send mail.
If you forget props.put("mail.smtp.ssl.protocols", "TLSv1.2"); you get javax.mail.MessagingException: Could not convert socket to TLS; and No appropriate protocol (protocol is disabled or cipher suites are inappropriate). Apparently this is only necessary for JavaMail versions 1.5.2 and older.
Here is the minimal code I required to get it to work:
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.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable","true");
// smtp.gmail.com supports TLSv1.2 and TLSv1.3
// smtp.office365.com supports only TLSv1.2
props.put("mail.smtp.ssl.protocols", "TLSv1.2");
props.put("mail.smtp.host", "smtp.office365.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("test#example.com", "******");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("sender#example.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient#example.com"));
message.setSubject("You got mail");
message.setText("This email was sent with JavaMail.");
Transport.send(message);
System.out.println("Email sent.");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
With Simple Java Mail 5.0.0 (simplejavamail.org) it is very straightforward and the library will take care of all the Session properties for you.
Here's an example using Google's SMTP servers:
Email email = EmailBuilder.startingBlank()
.from("lollypop", "lol.pop#somemail.com")
.to("C.Cane", "candycane#candyshop.org")
.withSubject("hey")
.withPlainText("We should meet up!")
.withHTMLText("<b>We should meet up!</b>")
.buildEmail();
MailerBuilder.withSMTPServer("smtp.gmail.com", 25, "user", "pass", SMTP_TLS)
.buildMailer()
.sendMail(email);
MailerBuilder.withSMTPServer("smtp.gmail.com", 587, "user", "pass", SMTP_TLS)
.buildMailer()
.sendMail(email);
MailerBuilder.withSMTPServer("smtp.gmail.com", 465, "user", "pass", SMTP_SSL)
.buildMailer()
.sendMail(email);
If you have two-factor login turned on, you need to generate an application specific password from your Google account.
As a small note, it only started to work for me when I changed smtp to smtps in the examples above per samples from javamail (see smtpsend.java, https://github.com/javaee/javamail/releases/download/JAVAMAIL-1_6_2/javamail-samples.zip, option -S).
My resulting code is as follow:
Properties props=new Properties();
props.put("mail.smtps.starttls.enable","true");
// Use the following if you need SSL
props.put("mail.smtps.socketFactory.port", port);
props.put("mail.smtps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtps.socketFactory.fallback", "false");
props.put("mail.smtps.host", serverList.get(randNum));
Session session = Session.getDefaultInstance(props);
smtpConnectionPool = new SmtpConnectionPool(
SmtpConnectionFactories.newSmtpFactory(session));
final ClosableSmtpConnection transport = smtpConnectionPool.borrowObject();
...
transport.sendMessage(message, message.getAllRecipients());

Categories