sending an email from java [duplicate] - java

This question already has answers here:
How can I send an email by Java application using GMail, Yahoo, or Hotmail?
(14 answers)
Sending Email using java program [duplicate]
(3 answers)
Closed 5 years ago.
i have been trying to send an email from my servlet. I tried to see how this can be done in the internet. But, in all the codes that I came across, none of them used the senders password to send the mail.
This means anyone can send an email from anyone's account. have I got it wrong or what is the actual matter?
Exception in thread "main" javax.mail.MessagingException: Could not connect to S
MTP host: localhost, port: 465;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:41
2)
at javax.mail.Service.connect(Service.java:288)
at javax.mail.Service.connect(Service.java:169)
at javax.mail.Service.connect(Service.java:189)
at Email1.main(Email1.java:19)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketI
mpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.ja
va:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocket
Impl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java
:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:612)
at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:160
)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359)

You're right in a way. Anyone can send am email pretending to be anybody else if smtp server doesn't require authentication ;-) Fortunately most servers out there do require authentication.
I didn't quite get what you're trying to achieve here. Do you have your own smtp server, or do you want to allow users to send mail from an account they already have (e.g. from gmail.com). In both cases you'll probably like to see JavaMail API documentation. There is even a sample JavaMailServlet you may use as reference.
Here's a simple program that sends an email and uses user/pass to authenticate to smtp server (based on examples in JavaMail):
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 Mail
{
public static void main(String[] args) throws MessagingException
{
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.example.com");
// props.setProperty("mail.smtp.auth", "true"); // not necessary for my server, I'm not sure if you'll need it
Session session = Session.getInstance(props, null);
Transport transport = session.getTransport("smtp");
transport.connect("user", "password");
Message message = new MimeMessage(session);
message.setSubject("Test");
message.setText("Hello :)");
message.setFrom(new InternetAddress("you#example.com"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress("your-friend#example.com"));
transport.sendMessage(message, message.getAllRecipients());
}
}

Sending an e-mail from a servlet is something you might do when you have code that is running a report or needs to notify you of some event, in which case, that e-mail will be from a generic service account. If you want to use a client's e-mail credentials, you will have to request them or have an UI that allows your users to enter contact information. I think it is kind of iffy to be asking anyone for their e-mail password, however. I know I would not enter that information into someone's website, no matter how much I trusted their service. So I think you need to think more about your design and what your expecations are as opposed to simply how to do it with code.

Related

java outlook client application getting 535 5.7.3 Authentication unsuccessful exception [duplicate]

I get this error when I try to send a mail using JavaMail API. I am sure that the username and password are 100% correct. The Gmail account which I'm connecting is an older account, because they say it takes time for it to work with new accounts.
DEBUG SMTP RCVD: 535-5.7.1 Username and Password not accepted. Learn more at
535 5.7.1 http://mail.google.com/support/bin/answer.py?answer=14257 x35sm3011668
wfh.6
javax.mail.SendFailedException: Sending failed;
nested exception is:
javax.mail.AuthenticationFailedException
at javax.mail.Transport.send0(Transport.java:218)
at javax.mail.Transport.send(Transport.java:80)
at Main.(Main.java:41)
at Main.main(Main.java:51)
and this is my code:
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class Main
{
String d_email = "abc#gmail.com",
d_password = "pass",
d_host = "smtp.gmail.com",
d_port = "465",
m_to = "abc#gmail.com",
m_subject = "Testing",
m_text = "testing email.";
public Main()
{
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.auth", "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");
SecurityManager security = System.getSecurityManager();
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);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
Transport.send(msg);
}
catch (Exception mex)
{
mex.printStackTrace();
}
}
public static void main(String[] args)
{
Main blah = new Main();
}
private class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(d_email, d_password);
}
}
}
I had same issue :
I refer this link, I have followed below steps it worked for me.
By default Gmail account is highly secured. When we use gmail smtp from non gmail tool, email is blocked. To test in our local environment, make your gmail account less secure as
Login to Gmail.
Access the URL as https://www.google.com/settings/security/lesssecureapps
Select "Turn on"
The given code snippet works fine on my Gmail account, so this problem lies somewhere else. Did you follow the link given in the error message? It contains the following hints:
Make sure that you've entered your full email address (e.g. username#gmail.com)
Re-enter your password to ensure that it's correct. Keep in mind that passwords are case-sensitive.
Make sure your mail client isn't set to check for new mail too often. If your mail client checks for new messages more than once every 10 minutes, your client might repeatedly request your username and password.
Especially the last point is important. Google is very strict in this. If you're trying to connect Gmail for example more than 10 times in a minute programmatically, then you may already get blocked. Have a bit of patience, after some time it will get unblocked.
If you'd like more freedom in sending mails, I recommend to look for a dedicated mail host or to setup your own mail server, such as Apache James or Microsoft Exchange. I've already answered this in detail in one of your previous questions.
I encountered the exact same problem, for me the reason is I have turned on 2-step verification on my gmail account.
After generating a new application-specific password and use that in my java application, this "535 5.7.1" issue is gone.
You can generate a new application-specific password following this official google guide.
I faced the same problem although my username and password were correct, but after some research, I was able to send email through applications by enabling the Less secure app access option on my Gmail account. You can find this feature under security option in the left menu.
Related links:
I can't sign in to my email client
Enable access to less secure applications
Now, Google not supported Less Secure Apps so we are getting this issue.
You follow bellow steps to resolve your Authentication issue during send mail using SMTP.
1 - Enable 2-step Verification in your mail
2 - Once you enabled above, you will able to see App Passwords option in same Security tab
3 - Now generate App Password for Other(Custom)
4 - Use this generated password in place of your gmail password in your code.
Enjoy :)
I have the same error message and this is how I have solved the issue,
Create an app password: here is how we can generate an app password,
1. Visit your App passwords page. You may be asked to sign in to your Google Account.
2. At the bottom, click Select app and choose the app you’re using.
Click Select device and choose the device you’re using.
3. Select Generate.
4. Follow the instructions to enter the App password (the 16 character code in the yellow bar) on your device.
5. Select Done.
I worked for a Spring boot app and I get the app password say, sadsadaffferere for the email address, xyz#gmail.com. So, I need to configure the app properties like the following,
# the email settings
# ------------------
spring.mail.host=smtp.gmail.com
spring.mail.username=xyz#gmail.com
spring.mail.password=sadsadaffferere
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.socketFactory.port=465
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback=false
support.email=xyz#gmail.com
Everything works fine afterwards
You need to turn on the 'less secure apps allowed' in gmail settings.
If the same credential was working earlier and it stopped working then the primary reason for this problem is password mismatch/changed on gmail client and not updated in Jenkins or other CI server. If that is not the case then check for reasons mentioned by #BalusC
i turned off antivirus and enabled less secure app in gmail, but now google has disabled this option, for that to work you need to do two steps verification and genetare 16 digit password and paste in application.properties replace this 16 digit password.

A question about sending email from java program

I need to send email from java program. I am first trying to understand basics. I found a snippet at:
https://www.javatpoint.com/example-of-sending-email-using-java-mail-api
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail
{
public static void main(String [] args){
String to = "sonoojaiswal1988#gmail.com";//change accordingly
String from = "sonoojaiswal1987#gmail.com";change accordingly
String host = "localhost";//or IP address
//Get the session object
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
//compose the message
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Ping");
message.setText("Hello, this is example of sending email ");
// Send message
Transport.send(message);
System.out.println("message sent successfully....");
}catch (MessagingException mex) {mex.printStackTrace();}
}
}
My question is that as per the code, it looks like anyone can use any sender email address string and send infinite emails to any receiver email address. I am missing something in my understanding, which will prevent such scenario to happen. Please help.
I understand that this is not a programming question, but guess, it will not take too much time to answer this basic question and don't know any other equally active forum.
This example works for servers which don't need authentication. And this is usually not applicable to the smtp servers used in production. Such servers are used mostly for testing purposes where they are not exposed over the internet. Hence, although its possible to send infinite number of mails as mentioned by you, no one would be interested in doing the same.
For the servers where authentication is necessary, credentials need to be provided. And this is explained in detail in the blog mentioned by you.

Automating existing web application and email generated report

I do have a java web application that is used for storing data about issues we faces daily.
There are many users and each user will be inserting data into it daily and by the end of day we'll gather that particular days data and then mail it to everyone.
We are using the web app to do this. But as of now web app generates consolidated data for one day when I trigger it using a button press.
And the code written to create excel sheet drafts a excel sheet and this one i mail to everyone. This web application is being run on a server.
I wish to automate this process i.e. each night at some specified time it should automatically trigger the function and generate the excel sheet and it should mail it to everyone.
I don't have much idea about how to go forward so I thought first I'll write java code to send mail and later think about triggering the function at a particular time.
I would like to know whether is there any other better way to deal with my requirement. I'am open to suggestions.
Also, the code I have written to send the mail is not working. It is giving me exception and I tried almost everything I could find but nothing is working. Could someone help me in sorting out the error.
Here's the code :
package com.email;
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 = "toemail#gmail.com";
// Sender's email ID needs to be mentioned
String from = "fromemail#gmail.com";
final String username = "username";//change accordingly
final String password = "password";//change accordingly
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);
}
}
}
Exception that I am receiving is :
Exception in thread "main" java.lang.RuntimeException: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 587; timeout -1;
nested exception is:
java.net.UnknownHostException: smtp.gmail.com
at com.tutorialspoint.SendEmail.main(SendEmail.java:62)
Caused by: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1;
nested exception is:
java.net.UnknownHostException: smtp.gmail.com
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2209)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:740)
at javax.mail.Service.connect(Service.java:388)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at javax.mail.Transport.send0(Transport.java:254)
at javax.mail.Transport.send(Transport.java:124)
at com.email.SendEmail.main(SendEmail.java:57)
Caused by: java.net.UnknownHostException: smtp.gmail.com
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:353)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:239)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2175)
... 7 more
According to the logs you cannot reach the gmail smtp. Are you maybe behind a proxy/firewall? Did you try pinging the smtp?
For running the tasks automatically you just need to add a scheduling framework to run the code at a certain time.
You could use quartz for example

Mail service GAE issue - sending mail exception "javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;"

I'd like to send mail from my GAE project. I've followed the documentation example...
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("xxx#xxxx.appspotmail.com", "Example.com Admin"));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress("xxxxx#gmail.com", "Mr. User"));
msg.setSubject("Your Example.com account has been activated");
msg.setText("This is a test");
Transport.send(msg);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
After deployment, I get this exception message
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
But the documentation says that:
When you create a JavaMail Session, if you do not provide any SMTP server configuration, App Engine uses the Mail service for sending messages
But it seems to try connecting to a SMTP server... and obviously there is no SMTP server on localhost...
I've never used this service... my quotas are full available.
Please, help me !
had the same issue today. just got it working. app engine sdk already includes the classes you will need to send email:
https://cloud.google.com/appengine/docs/standard/java/javadoc/com/google/appengine/api/mail/MailService.Message
that and the related classes are the way to invoke the mail service. replace your message classes with those, remove all references to javax.mail. one other thing in case you're referencing this (as I was):
https://cloud.google.com/appengine/docs/standard/java/mail/sending-mail-with-mail-api
I couldn't get it to work, doesn't looks like it would without an smtp host at least. Nice of google to provide nonsensical documentation for a non-working example in their example code base
also, if you follow the "who can send mail" link it tells you that any address of the form anything#[APP_NAME].appspotmail.com or anything#[APP_ALIAS].appspotmail.com should work. using my apps name resulted in "unauthorized sender", but using the app id from the dashboard worked. what should have been a ten minute solution turned into hours of drudgery, but I have a working emailer. thanks, google.
The Mail service API supports the JavaMail (javax.mail) interface which is included with the App Engine SDK. Using any other jars may create the issue. You may follow the code sample in Java 7 and Java 8 which demonstrate how to send mail.
I should note that outbound connections on ports 25, 465, and 587 are not allowed due to spam concerns, so the sender address of a message must be one of the optioned in this link.
You can take your application ID/name (which is the same as the project ID/name) through the dashboard.
Kindly note that Issue Tracker is reserved for reporting bugs and feature requests. If you encounter any issue related to APP_NAME or APP_ALIAS, it is recommended to report the issue there so that we would be able to dig into the problem.

Sending email with java Apache Commons Mail through Lotus Notes

I'm having trouble with my e-mail configuration for sending e-mails using lotus notes in a java program. I know this is pretty much straight forward but i guess i'm missing something. My code is as follows;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
public class MailClass {
public void SendMail() {
SimpleEmail email = new SimpleEmail();
try {
email.setHostName("mail.smtp.host");
email.addTo("recipient#company.com");
email.setFrom("sender#agency.com");
email.setSubject("Hello World");
email.setMsg("This is a simple test of commons-email");
email.send();
} catch (EmailException ex) {
Logger.getLogger(MailClass4.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
MailClass main = new MailClass();
main.SendMail();
}
}
I keep on getting this error
SEVERE: null
org.apache.commons.mail.EmailException: Sending the email to the following server failed : mail.smtp.host:25
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1242)
...
Caused by: javax.mail.MessagingException: Unknown SMTP host: mail.smtp.host;
nested exception is:java.net.UnknownHostException: mail.smtp.host at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1970)
I'm guessing it's about my host but not really sure what to do about it. From my understanding your host should be your email client (ex. mail.smtp.google.com). But since this is Lotus Notes (it runs in our intranet btw) the implimentation will be different. I've seen other samples that use the "mail.smtp.host" as host but i can't get this one right....
It's my first time doing an e-mail program so i'm pretty much clueless about this.
You can use your Domino server running on your intranet as SMTP server but first you have to ask your admin if Domino has been set up to allow SMTP - and at the same time ask for the proper host name and port).
setHostName requires the hostname or IP-address of a smtp server. And the exception makes it very clear what the issue is.
Lotus Notes is basicslly just a client and has nothing to do with what you are trying to accomplish.

Categories

Resources