I integrated in my JavaMail application, allowing me to send an email via Java (I use Gmail) it works without problems but when I use it on another connection, it no longer works.
He shows me this error :
enter image description here
There is my Mail code :
public class SupportMail {
private static String LOGIN_SMTP1="login";
private static String PASSWORD_SMTP1="pwd";
private static String SMTP_HOST1="smtp.gmail.com";
private static String IMAP_ACCOUNT1="rollandgame#gmail.com";
private static String receiver = "floriangenicq#gmail.com";
private static String copyRecei = "floriangenicq#gmail.com";
public SupportMail() {
}
public static void sendMessage(String subject, String text) {
// Création de la session
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", "smtp");
properties.put("mail.smtp.ssl.trust", SMTP_HOST1);
properties.setProperty("mail.smtp.host", SMTP_HOST1);
properties.setProperty("mail.smtp.user", LOGIN_SMTP1);
properties.setProperty("mail.from", IMAP_ACCOUNT1);
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.port", 587);
properties.put("mail.smtp.auth", "true");
Session session = Session.getInstance(properties);
// Création du message
MimeMessage message = new MimeMessage(session);
try {
message.setText(text);
message.setSubject(subject);
} catch (MessagingException e) {
e.printStackTrace();
}
// Envoie du mail
Transport transport = null;
try {
transport = session.getTransport("smtp");
transport.connect(LOGIN_SMTP1, PASSWORD_SMTP1);
transport.sendMessage(message, new Address[] { new InternetAddress(receiver),
new InternetAddress(copyRecei) });
} catch (MessagingException e) {
e.printStackTrace();
} finally {
try {
if (transport != null) {
transport.close();
}
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
Try using lesser secure settings in your gmail config
https://myaccount.google.com/intro/security
Related
My company mail domain is Gmail , and I need to search a mail using subject line. I have written below code but Gmail is not connecting with correct user id and password.
public static void getMail() {
Scanner sc = new Scanner(System.in);
final String m10 = "abc#abc.com";
final String n10 = "abcd";
String host = "absmtp.abc.com";
try
{
Properties pro1 = new Properties();
pro1.put("mail.smtp.host", host);
pro1.put("mail.smtp.socketFactory.port", "465");
MailSSLSocketFactory socketFactory= new MailSSLSocketFactory();
socketFactory.setTrustAllHosts(true);
pro1.put("mail.imaps.ssl.socketFactory", socketFactory);
// pro1.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// pro1.put("mail.smtp.auth", "true");
pro1.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(pro1);
Store store = session.getStore("imaps");
store.connect(host, m10, n10);
Folder folderbox = store.getFolder("INBOX");
folderbox.open(Folder.READ_ONLY);
SearchTerm search = new SearchTerm(){
#Override
public boolean match(Message message) {
try
{
if(message.getSubject().contains("") )
{
return true;
}
}
catch(Exception e)
{
System.err.println(e.getMessage());
}
return false;
}
};
Message[] found = folderbox.search(search);
int length = found.length;
for(int i = 0;i<found.length;i++)
{
Message mess1 = found[i];
System.out.println("->Message Number > "+i);
System.out.println("->Message Subject >"+mess1.getSubject());
}
folderbox.close(true);
store.close();
}
catch(Exception e)
{
System.err.println(e.getMessage());
}
}
is not connecting and giving error :
Couldn't connect to host, port: abc#abc.com, 993; timeout -1.
I want to read HTML file and want to send HTML formatted email.
public class SendEmailer {
public void sendHtmlEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) throws AddressException,
MessagingException {
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// sets SMTP server properties
Properties properties = new Properties();
properties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
properties.setProperty("mail.smtp.socketFactory.fallback", "false");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.store.protocol","pop3");
properties.put("mail.transport.protocol","smtp");
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
// set plain text message
msg.setContent(message, "text/html");
// sends the e-mail
Transport.send(msg);
}
//Code to read HTML document.
public void readHTML(String strfilename,String content){
// content="";
String str="";
try{
FileReader fr=new FileReader(strfilename);
BufferedReader br=new BufferedReader(fr);
while((str=br.readLine())!=null){
System.out.println(str.toString());
content+=str;
}
br.close();
}catch(IOException ie){
ie.printStackTrace();
}
}
public static void main(String[] args) {
// SMTP server information
String host = "myhost.com";
String port = "465";
String mailFrom = "abc#myhost.com";
String password = "abcd123";
// outgoing message information
String mailTo = "abc#gmail.com";
String subject = "Test mail";
// message contains HTML markups
String message = "<i>Greetings!Sending HTML mail.</i><br>";
message += "<font color=red>MyName</font>";
SendEmailer mailer = new SendEmailer ();
String filename="E:/filepath/filename.html";
try {
mailer.readHTML(filename);
mailer.sendHtmlEmail(host, port, mailFrom, password, mailTo,
subject, message);
System.out.println("Email sent successfully.");
} catch (Exception ex) {
System.out.println("Failed to sent email.");
ex.printStackTrace();
}
}
}
I am able to send email successfully. But now I want to send the full body part of the html file. I wrote a method readHTML(), but its not reading the content of that file neither it sends the same. It sends only what I've stored in message variable. Where did I make mistake?
The following code works only when Google's "Allow less secure apps" is ON, if that feature is off I get javax.mail.AuthenticationFailedException, how do I get it to work when that feature is OFF?
public static void main(String[] args) {
String username = "USER-NAME#gmail.com";
String password = "PASSWORD";
String to = "USER-NAME#msn.com";
Properties properties = new Properties();
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
properties.setProperty("mail.smtp.port", "587");
properties.list(System.out);
Session session = Session.getInstance(properties);
MimeMessage msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(username));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject("This is the subject line!");
msg.setText("This is the actual message");
System.out.println("Sending message...");
Transport.send(msg, username, password);
System.out.println("Message sent!");
} catch (MessagingException ex) {
Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, null, ex);
} finally {
}
}
I'm trying to create a program using the JavaMail API, however, I keep getting the following error message.
javax.mail.NoSuchProviderException: invalid provider
at javax.mail.Session.getTransport(Session.java:738)
at javax.mail.Session.getTransport(Session.java:682)
at javax.mail.Session.getTransport(Session.java:662)
at EmailAutoResponder2.main(EmailAutoResponder2.java:56)
I was not able to solve it by reading online, as all of their solutions still gave me the same message.
Here is the Java code:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailAutoResponder2 {
public static void main(String[] args) {
String to = "username#videotron.ca";
String from = "username#videotron.ca";
Properties properties = System.getProperties();
properties.setProperty("mail.store.protocol", "imaps");
Session session1 = Session.getInstance(properties);
//If email received by specific user, send particular response.
Properties props = new Properties();
props.put("mail.imap.auth", "true");
props.put("mail.imap.starttls.enable", "true");
props.put("mail.imap.host", "imap.videotron.ca");
props.put("mail.imap.port", "143");
Session session2 = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username#videotron.ca", "password");
}
});
try {
Store store = session2.getStore("imap");
store.connect("imap.videotron.ca", "username#videotron.ca", "password");
Folder fldr = store.getFolder("Inbox");
fldr.open(Folder.READ_ONLY);
Message msgs[] = fldr.getMessages();
for(int i = 0; i < msgs.length; i++){
System.out.println(InternetAddress.toString(msgs[i].getFrom()));
if (InternetAddress.toString(msgs[i].getFrom()).startsWith("Name")){
MimeMessage message = new MimeMessage(session1);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Subject");
message.setText("Message");
String protocol = "imap";
props.put("mail." + protocol + ".auth", "true");
Transport t = session2.getTransport("imap");
try {
t.connect("username#videotron.ca", "password");
t.sendMessage(message, message.getAllRecipients());
}
finally {
t.close();
}
}
}
}
catch(MessagingException mex){
mex.printStackTrace();
}
catch(Exception exc) {
}
}
}
Thank you!
You're connecting to localhost to send the message. Do you have a mail server running on your local machine? Probably not. You need to set the mail.smtp.host property. You may also need to supply a username and password for your mail server; see the JavaMail FAQ.
The following code may solve your problem
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "username"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "password"; // GMail password
private static String RECIPIENT = "xxxxx#gmail.com";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "hi ....,!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.trust", 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");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
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++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
To verify smtp server credentials shall I use transport.connect()?
Session session = Session.getInstance(properties,authenticator);
Transport tr=session.getTransport("smtp");
tr.connect();
Is it correct method to check smtp server credentials?
This question: 'Verify mail server connection programmatically in ColdFusion' has a java solution as part of the accepted answer:
int port = 587;
String host = "smtp.gmail.com";
String user = "username#gmail.com";
String pwd = "email password";
try {
Properties props = new Properties();
// required for gmail
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");
// or use getDefaultInstance instance if desired...
Session session = Session.getInstance(props, null);
Transport transport = session.getTransport("smtp");
transport.connect(host, port, user, pwd);
transport.close();
System.out.println("success");
}
catch(AuthenticationFailedException e) {
System.out.println("AuthenticationFailedException - for authentication failures");
e.printStackTrace();
}
catch(MessagingException e) {
System.out.println("for other failures");
e.printStackTrace();
}
public boolean confirmSMTP(String host, String port, String username, String password, String auth, String enctype) {
boolean result = false;
try {
Properties props = new Properties();
if (auth.equals(true)) {
props.setProperty("mail.smtp.auth", "true");
} else {
props.setProperty("mail.smtp.auth", "false");
}
if (enctype.endsWith("TLS")) {
props.setProperty("mail.smtp.starttls.enable", "true");
} else if (enctype.endsWith("SSL")) {
props.setProperty("mail.smtp.startssl.enable", "true");
}
Session session = Session.getInstance(props, null);
Transport transport = session.getTransport("smtp");
int portint = Integer.parseInt(port);
transport.connect(host, portint, username, password);
transport.close();
result = true;
} catch(AuthenticationFailedException e) {
Logging.addMsg(e.toString(), "SMTP: Authentication Failed", false, true);
} catch(MessagingException e) {
Logging.addMsg(e.toString(), "SMTP: Messaging Exception Occurred", false, true);
} catch (Exception e) {
Logging.addMsg(e.toString(), "SMTP: Unknown Exception", false, true);
}
return result;
}