Trying to send an email using my gmail account like bellow -
import org.junit.jupiter.api.Test;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class EMailTest {
#Test
public void sendEmail() {
String to = "to-email#markany.com";
String from = "from-email#gmail.com";
String host = "smtp.gmail.com";
Properties properties = System.getProperties();
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");
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, "from-email-password");
}
});
session.setDebug(true);
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");
System.out.println("sending...");
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
But it required turning on the "Less secure app access" option in sender/from email account setting.
And this option is no longer supported by Gmail -
https://support.google.com/accounts/answer/6010255?hl=en
So, how to send email now in Java using Gmail?
Related
I am trying to send mail using Java code . The code is working fine when running on my personal PC . But on office network the exception of unknown SMTP host is appearing. Also my office pc is not able to ping smtp.gmail.com. PC firewall is closed as well.
Is there any other way to establish the connection? I am also providing my code below for reference.
mport javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import javax.mail.Authenticator;
public class otp {
String d_email = "email#gmail.com",
d_password = "password",
d_uname="uname",//your email password
d_host = "mail.outlook.com",
d_port = "587",
m_to = "target#gmail.com", // Target email address
m_subject = "Testing Mail programs",
m_text = "Hey, this is a test email.";
public otp() {
Properties props = new Properties();
props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", d_host);
props.put("mail.smtp.port", d_port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.debug", "true");
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");
try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props,auth);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
msg.setText(m_text);
msg.setSubject(m_subject);
System.out.println(1);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
System.out.println(3);
Transport transport = session.getTransport("smtp");
transport.connect(d_host, Integer.valueOf(d_port),d_uname , d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
Transport.send(msg);
System.out.println("Message Sent succesfully");
} catch (Exception mex) {
mex.printStackTrace();
}
}
public static void main(String[] args) {
otp blah = new otp();
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(d_email, d_password);
}
}
}
I guess that you are behind the internal firewall/proxy of your office, it is very common to put the whole internal network of a company behind a central firewall or to check Outgoing/Incoming requests of the networks traffic a Dynamic Proxy Server.in that case, you can check it in the proxy settings of your pc.
internet explorer(or any browser)-> settings -> internet option -> Connections Tab -> LAN Settings.
for the granular analyses,please attach your code.
you are using a gmail account but you have provided a outlook host , try the following template:
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 SendEmailUsingGMailSMTP {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "xyz#gmail.com";//change accordingly
// Sender's email ID needs to be mentioned
String from = "abc#gmail.com";//change accordingly
final String username = "abc";//change accordingly
final String password = "*****";//change accordingly
// >> gmail host
String host = "smtp.gmail.com";
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", "587");
// 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);
}enter code here
}
}
The following is my code.
This executed successfully. But I didn't see any mail in my inbox
Anybody please help.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendMail {
public static void main(String args[]) throws Exception {
String fromAddress = "testmail#gmail.com";
String toAddress = "testmail#gmail.com";
Properties properties = new Properties();
properties.put("mail.smtp.host", "localhost");
properties.put("mail.smtp.port", "25");
properties.put("mail.transport.protocol", "smtp");
try
{
properties.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(properties, null);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromAddress));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));
message.setSubject("Email from our JAMEs");
message.setText("hiiiiii!!");
Transport.send(message);
System.out.println("Email sent");
}
catch (MessagingException e)
{
e.printStackTrace();
}
}
}
You'll need to either login and send over one of:
POP
IMAP
Gmail API
or you can use a domain you control, at the moment you are trying to send as gmail.com, and being ignored because it knows your IP is not allowed to send as gmail.com, because of SPF, which limits spam by setting who can send as which domains
SPF (Wikipedia)
I am wondering why the below basic java mail program is not working because I didn't get any errors as the program is executed just fine. Is there anything that I am doing wrong? Any help would be appreciated.I would also like to add that I also tried it using wrong username and password combination but still getting no error and the programs runs completely fine.
public class emailfromgmail {
public static void main(String[]args)
{
final String from = "username";
final String pass = "password";
String to = "recipient#gmail.com";
String host="smtp.gmail.com";
String subject = "java Mail";
String body = "example of java mail api using gmail smtp";
//get the session object
Properties p = System.getProperties();
p.put("mail.smtp.starttls.enable","true");
p.put("mail.smtp.host",host);
p.put("mail.smtp.user",from);
p.put("mail.smtp.password",pass );
p.put("mail.smtp.port", "587");
p.put("mail.smtp.auth","true");
Session session = Session.getInstance(p,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, pass);
}
});
try{
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
msg.setSubject(subject);
msg.setText(body);
Transport.send(msg);
System.out.print("message sent successfully");
}
catch(MessagingException e){
e.printStackTrace();
}
}
}
I had the same problem - I ran my program and put in a dialogue box in various places to see where it stopped doing anything. I still don't know what was wrong, but I tried a totally different approach and it worked. Instead of sending via TLS, I send via SSL. I used this website:
https://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
Their TLS didn't work - it just didn't do anything when I ran it. Their SSL worked like a charm!
Here is the code:
package com.mkyong.common;
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 SendMailSSL {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username","password");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from#no-spam.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to#no-spam.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);
}
}
}
i am creating a simple java mail program,the program is working ok and the last system print also working .but the problem is i dint received the mail in outlook.here i am using the company outlook.please some one help me.
i am attaching my code here
enter code here
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SimpleSendEmail
{
public static void main(String[] args)
{
String host = "compny host";
String from = "mail id";
String to = "usr#some.com";
String subject = "birthday mail";
String messageText = "I am sending a message using the"
+ " simple.\n" + "happy birthday.";
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("compny host", host);
props.put("mail.smtp.port", "25");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(props, null);
// Set debug on the Session so we can see what is going on
// Passing false will not echo debug info, and passing true
// will.
session.setDebug(sessionDebug);
try
{
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = { new InternetAddress(to) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
Transport.send(msg);
System.out.println("Sent message successfully....");
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
}
output
Sent message successfully....
"Compny host" doesn't seem like correct host. Check out this tutorial http://www.tutorialspoint.com/java/java_sending_email.htm and here you have also a few examples of sending emails in Java Send email using java
I do expect that you are using the correct host on your side.
But you are missing Username and Password.
transport = session.getTransport("smtp");
transport.connect(hostName, port, user, password);
transport.sendMessage(message, message.getAllRecipients());
or you can use the Authenticator:
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
I would like to send email without authentication using java.
Can someone help me?
With authentication, I do it as follows:
public void sendEmail() throws EmailException{
SimpleEmail email = new SimpleEmail();
email.setHostName("smtp.gmail.com");
email.setSmtpPort(465);
email.addTo("XXX#gmail.com", "XXXX");
email.setFrom("XXXX#gmail.com","XXXXX");
email.setSubject("testando . . .");
email.setMsg("testando 1");
email.setSSL(true);
email.setAuthentication("xxxxxx#gmail.com", "XXXXX");
email.send();
}
I forgot to say that i do not have a provider. i need an provider finally, i have emailFrom Subject and Message, and need send this email how?
If it is only for testing purposes, you may try Papercut. While it’s running, Papercut automatically picks up e-mail sent to the standard SMTP port (25) on any IP address. You just send mail from your application and switch to Papercut to review it.
Papercut # github:
https://github.com/ChangemakerStudios/Papercut/releases
import java.util.Date;
import java.util.Properties;
import javax.mail.Message.RecipientType;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.put("mail.smtp.host", "127.0.0.1");
props.put("mail.smtp.port", "25");
props.put("mail.debug", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("admin#test.com"));
message.setRecipient(RecipientType.TO, new InternetAddress("a#b.com"));
message.setSubject("Notification");
message.setText("Successful!", "UTF-8"); // as "text/plain"
message.setSentDate(new Date());
Transport.send(message);
}
}
import java.util.*;
import javax.mail.*;
public class SimpleEmail {
public static void main(String[] args) {
System.out.println("SimpleEmail Start");
String smtpHostServer = "smtp.gmail.com";
String toEmail = "XXXX#gmail.com";
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHostServer);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.port", "25");
Session session = Session.getDefaultInstance(props);
try {
MimeMessage msg = new MimeMessage(session);
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("n91eply#gmail.com", "NoReply-JD"));
msg.setReplyTo(InternetAddress.parse("n91eply#gmail.com", false));
msg.setSubject("SimpleEmail Testing Subject", "UTF-8");
msg.setText("SimpleEmail Testing Body", "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
System.out.println("Message is ready");
Transport.send(msg);
System.out.println("EMail Sent Successfully!!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Try this example:
// File Name SendEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "abcd#gmail.com";
// Sender's email ID needs to be mentioned
String from = "web#gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
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");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Via: tutorialspoint