How to send an email from a PC by a Java program? - java

What is required for sending mail from my computer by a Java program? I mean any changes, like enabling or disabling options, should be done from the PC.

Java has built in libraries for that.
import javax.mail.*;
import javax.mail.internet.*;
are the libraries you will need.
You need to have mail.jar in your classpath because it is not part of core Java.

You should have access to an SMTP server through which you mail can be sent. Also you will need to check that any firewall you have installed allows outgoing traffic on port 25 to communicate with the SMTP server.
Edit: if, as you mention below, you have no SMTP server access, you could sign up for a gmail account for your application and make use of the Gmail SMTP server (obviously not ideal for a business app, but perfectly fine as a personal app. For instruction on how to set this up, read this Lifehacker post.

The canonical way of creating and sending MIME-based email messages from Java (so it can contain HTML and images), is using JavaMail which is a very capable package, and which can even be taught to send mail through GMail over SSL if you do not have an internal SMTP-server available.
See http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/ for two examples of how to do it.

Just change the email address and password. This example uses gmail. Also, you can have as many recipients as you wish.
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 AnotherMail {
public static void main(String... args) {
String host = "smtp.gmail.com";
String from = "myEmail#gmail.com";
String pass = "MyPassword";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true"); // added this line
props.put("mail.smtp.host", 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");
String[] to = {"someRecipient#gmail.com"}; // added this line
try {
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
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++) { // changed from a while loop
toAddress[i] = new InternetAddress(to[i]);
}
System.out.println(Message.RecipientType.TO);
for (int i = 0; i < toAddress.length; i++) { // changed from a while loop
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException mx) {
mx.printStackTrace();
}
}
}

Related

How to deal with "avax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted" when less secure app feature is not available

I'm trying to send an email using java.
This is my code.
All my credentials are correct but still I get this error.
I have seen many solutions which says turn on less secure apps but that feature is now disabled by google.
so how do I solve it.
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 SendEmail {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "sender#gmail.com";
// Sender's email ID needs to be mentioned
String from = "receiver#gmail.com";
// Assuming you are sending email from through gmails smtp
String host = "smtp.gmail.com";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", "465");
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// Get the Session object.// and pass username and password
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("receiver#gmail.com", "password");
}
});
// Used to debug SMTP issues
session.setDebug(true);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
System.out.println("sending...");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
This is the error I'm getting.
my error in vs code
Since the less secure app feature is removed we have to follow these below steps to use Gmail via third party software that is App password
Step 1: setup 2-Step Verification:- Google Account -> Security -> 2-Step Verification -> Input password as asked -> Turn ON (you could use SMS to get Gmail code to activate 2-Step Verification)
Step 2: Generate app secret:- Google Account -> Security -> App password -> Input password as asked -> Select the app and device... -> e.g. Other(Java application) -> Input app name e.g. MyApp -> Generate
Step 3: Use generated app secret:- Copy a 16-character password
Use a 16-character password (instead of actual password) with Gmail username in your application
This should save your day

Exception in thread "main" java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 535 5.7.8 Authentication credentials invalid

This piece of code is picked up from http://www.tutorialspoint.com/javamail_api/javamail_api_sending_simple_email.htm
//package com.tutorialspoint;
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 SendEmail {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "ABC#gmail.com";
// Sender's email ID needs to be mentioned
String from = "PQR#gmail.com";
final String username = "NAME";
final String password = "****";
// Assuming you are sending email through relay.jangosmtp.net
String host = "relay.jangosmtp.net";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25");
// Get the Session object.
Session session = Session.getInstance(props,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Testing Subject");
// Now set the actual message
message.setText("Hello, this is sample for to check send "
+ "email using JavaMailAPI ");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
I tried getting hint from this link. But it seems to be using a slightly different method.
On running it with a debugger, exception seems to be coming from following code:
Transport.send(message);
Following is the stack trace:
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:809)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:752)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:669)
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)
at SendEmail.main(SendEmail.java:58)
PS: I have checked the username and password. Also, 2 step sign in process is not enabled for the account from which I am trying to send mail.
Can someone please explain what could be the cause of authenticatio failure? Alternatively, if there is some other post which has already answered the query, please point me to it. Thanks.
The server isn't happy with the username or password you're using. You can probably guess the common reasons that might be the case, staring with you provided the wrong username or password.
The JavaMail Session debugging output might provide more information.
change String host = "relay.jangosmtp.net";
to String host = "smtp.gmail.com";
and Port from 25 to 587

How to send mail in Java using same mechanism like in PHP mail()

I'm having trouble in sending mail from my application. I can't use simple SMTP server on my application. And have no idea how to deal with sending mails in JAVA. I'm supposed to use same/similar mechanism like PHP's mail() uses. Unfortunately I have no idea how to do it.
The Java Mail API provides support for sending and receiving e-mails. The API provides a plug-in architecture where vendor’s implementation for their own proprietary protocols can be dynamically discovered and used at the run time. Sun provides a reference implementation and its supports the following protocols:
Internet Mail Access Protocol (IMAP)
Simple Mail Transfer Protocol (SMTP)
Post Office Protocol 3 (POP 3)
Here is an example of how to use it:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
private String from;
private String to;
private String subject;
private String text;
public SendMail(String from, String to, String subject, String text){
this.from = from;
this.to = to;
this.subject = subject;
this.text = text;
}
public static void main(String[] args) {
String from = "abc#gmail.com";
String to = "xyz#gmail.com";
String subject = "Test";
String message = "A test message";
SendMail sendMail = new SendMail(from, to, subject, message);
sendMail.send();
}
public void send(){
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
Session mailSession = Session.getDefaultInstance(props);
Message simpleMessage = new MimeMessage(mailSession);
InternetAddress fromAddress = null;
InternetAddress toAddress = null;
try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
} catch (AddressException e) {
e.printStackTrace();
}
try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
Transport.send(simpleMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
You need to check out the JavaMail API, and as PHP's mail() requires, it will need an SMTP server to send that email.
If you require an SMTP server I suggest searching Google for an SMTP server for your operating system or maybe you could use an SMTP server provided by your ISP or server host.
You can use JavaMail api with a local SMTP server like Apache James, so after installing and running James server, you can set the SMTP server ip to 127.0.0.1
I'm supposed to use same/similar mechanism like PHP's mail() uses.
You can't, because it doesn't exist. If that's the requirement, get it changed.
Unfortunately I have no idea how to do it.
See the JavaMail API.

Having trouble sending to Gmail SMTP using javax.mail

I want to send a mail using Gmail's SMTP server. Can you tell me why it won't connect to server when I run the bellow code.
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
public class SendTrick {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "465");
props.put("mail.from", "example#gmail.com");
props.put("mail.smtp.host", "smtp.gmail.com");
Session session = Session.getInstance(props, null);
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO,
"ex#gmail.com");
msg.setSubject("JavaMail hello world example");
msg.setText("Hello, world!\n");
Transport.send(msg);
} catch (MessagingException mex) {
System.out.println("send failed, exception: " + mex);
}
}
}
The exception in the log is
send failed, exception: javax.mail.MessagingException: Could not
connect to SMTP host: smtp.gmail.com, port: 25; nested exception is:
java.net.ConnectException: Connection refused: connect
You are not setting a mail.smtp.port since there is a duplication typo on the property mail.smtp.host, therefore the default port 25 is being used, as detailed in the the Exception.
GMail's SMTP is not running on port 25, which is why the connection is being refused. From Set up POP in mail clients, it looks like it should be 465 or 587, so you have a valid value but the property key is incorrect.
Edit:
You need use the correct property key for the port:
props.put("mail.smtp.port", "465"); // <-- use the word "port", not "host"
After this is fixed, you may also find authentication issues, as already noted in the comments, unless you have purposely left out the javax.mail.Authenticator code in the question.
Edit 2:
As I mentioned, you might need to specify additional properties to successfully authenticate and be authorised with the SMTP server, for example:
props.put("mail.smtp.starttls.enable", "true");
But, since you are using port 465 for SSL connection you will also need to specify additional SSL properties such as the mail.smtp.socketFactory.class.
Follow this steps:
Disable "Two factor authentication" in Your Email
Navigate to: "https://myaccount.google.com/lesssecureapps?pli=1" and turn on "Access for less secure apps"
Download JavaMail API "https://www.oracle.com/technetwork/java/javamail/index-138643.html" and Add it to your library
CODE
import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class email_try {
public static void main(String ap[]) {
String myEmail = "YOUR EMAIL";
String password = "YOUR PASSWORD";
String opponentEmail = "THEIR EMAIL";
Properties pro = new Properties();
pro.put("mail.smtp.host", "smtp.gmail.com");
pro.put("mail.smtp.starttls.enable", "true");
pro.put("mail.smtp.auth", "true");
pro.put("mail.smtp.port", "587");
Session ss = Session.getInstance(pro, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(myEmail, password);
}
});
try {
Message msg = new MimeMessage(ss);
msg.setFrom(new InternetAddress(myEmail));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(opponentEmail));
msg.setSubject("Your Wish");
msg.setText("java email app");
Transport trans = ss.getTransport("smtp");
Transport.send(msg);
System.out.println("message sent");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
TRY THIS CODE AND PUT CORRECT EMAIL ID AND PASSWORD

How do I send an SMTP Message from Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you send email from a Java app using Gmail?
How do I send an SMTP Message from Java?
Here's an example for Gmail smtp:
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.mail.internet.*;
import com.sun.mail.smtp.*;
public class Distribution {
public static void main(String args[]) throws Exception {
Properties props = System.getProperties();
props.put("mail.smtps.host","smtp.gmail.com");
props.put("mail.smtps.auth","true");
Session session = Session.getInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("mail#tovare.com"));;
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("tov.are.jacobsen#iss.no", false));
msg.setSubject("Heisann "+System.currentTimeMillis());
msg.setText("Med vennlig hilsennTov Are Jacobsen");
msg.setHeader("X-Mailer", "Tov Are's program");
msg.setSentDate(new Date());
SMTPTransport t =
(SMTPTransport)session.getTransport("smtps");
t.connect("smtp.gmail.com", "admin#tovare.com", "<insert password here>");
t.sendMessage(msg, msg.getAllRecipients());
System.out.println("Response: " + t.getLastServerResponse());
t.close();
}
}
Now, do it this way only if you would like to keep your project dependencies to a minimum, otherwise i can warmly recommend using classes from apache
http://commons.apache.org/email/
Regards
Tov Are Jacobsen
Another way is to use aspirin (https://github.com/masukomi/aspirin) like this:
MailQue.queMail(MimeMessage message)
..after having constructed your mimemessage as above.
Aspirin is an smtp 'server' so you don't have to configure it. But note that sending email to a broad set of recipients isnt as simple as it appears because of the many different spam filtering rules receiving mail servers and client applications apply.
Please see this post
How can I send an email by Java application using GMail, Yahoo, or Hotmail?
It is specific to gmail but you can substitute your smtp credentials.
See the following tutorial at Java Practices.
http://www.javapractices.com/topic/TopicAction.do?Id=144
See the JavaMail API and associated javadocs.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public void postMail(String recipients[], String subject,
String message , String from) throws MessagingException {
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.jcom.net");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(false);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Optional : You can also set your custom headers in the Email if you Want
msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}

Categories