Java Constructor not defined - java

Trying to send an email through my test, it calls on this class as the main one.
public class SendMail{
public SendMail(String fromMail,String tomail, Exception e )
{
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("abc123#gmail.com","testpw");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromMail));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(tomail));
message.setSubject("xxxxx");
message.setText("xxxxx"+ ExceptionUtils.getStackTrace(e) );
Transport.send(message);
System.out.println("Done");
}
catch (MessagingException ex) {
throw new RuntimeException(ex);
}
}
public SendMail(String string, String line) {
So I want to call this in my other class, to be able to pull a list of emails from a txt file so it will email everything on the list. That code is:
String fileName = "/xxx/xxx/xxx/text.txt";
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) !=null) {
new SendMail("abcd#gmail.com", line);
}
}
catch (IOException e) {
e.printStackTrace();
}
The problem is that it's telling me the constructor SendMail(String, String) is undefined.
My orginal code works but this only allows me to send hard coded emails.
try{
}
catch(Exception e)
{
e.printStackTrace();
new SendMail("senderemail","reciveremail",e); }
}
Why won't it accept my constructor?
EDIT: The consturctor was not wrong. I was! I found the reason why It wouldn't work and solved my issue. This is the code I'm using now that works.
String fileName = "/Users/cdolan/Desktop/liness.txt";
String Email = "";
try(BufferedReader br = new BufferedReader(new FileReader(fileName))) {
while ((Email = br.readLine()) !=null)
{
<Test code here goes here>
}
}
catch(Exception e)
{
e.printStackTrace();
new SendMail("email123#gmail.com",Email,e); }
}

The problem is that you only define the method SendMail(String fromMail,String tomail, Exception e) so you cant call a method that is not defined.
You need to define and implement the methodSendMail(String fromMail,String tomail,) so you can call it!
Another question should be: for what reason do you need to pass the exception as a input param?

The constructor you have specified takes an Exception as an argument (for what reason??). This exception argument is missing when you create a new object.

Related

Probleme with JavaMail

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

Java sending a mail via tomcat server

I'm trying to send a mail via android application, the mail has to be sent through my server (because the mail API of Gmail need username and password so, I don't want that my data be in the code itself)
but I got this error of socketTimeOutException.
I can increase the timeout but then I cannot do anything until the response received, and it takes like 25 seconds.
and if I put the sending function in a thread it doesn't send the mail at all.
this is the code of the server:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
JSONObject res = new JSONObject();
try {
System.out.println("Post ForgotMypass");
Mongo mongo = new Mongo(LogIn.host, 27017);
DB db = mongo.getDB("Users");
DBCollection collection = db.getCollection("usersCollection");
// get a myUser object and cheack for jobs
String json = request.getParameter("JSONObj");
JSONParser jp = new JSONParser();
JSONObject temp = (JSONObject) jp.parse(json);
String mail = (String) temp.get("mail");
if (mail != null) {
BasicDBObject searchQuer = new BasicDBObject();
searchQuer.put("Mail", mail);
DBObject Item = collection.findOne(searchQuer);
if (Item != null) {
JSONParser jp2 = new JSONParser();
JSONObject Is = (JSONObject) jp2.parse(Item.toString());
JSONObject I = (JSONObject) Is.get("_id");
String id = (String) I.get("$oid");
if (id != null) {
String Dmail = URLDecoder.decode(mail, "UTF-8");
SendMailSSL.SendMail(Dmail, 4, id);
StringWriter out = new StringWriter();
res.put("Status", "true");
res.writeJSONString(out);
response.getOutputStream().println(out.toString());
System.out.println("mail sent succesfully");
} else {
StringWriter out = new StringWriter();
res.put("Status", "falseNoMail");
System.out.println("ver false no mail");
res.writeJSONString(out);
response.getOutputStream().println(out.toString());
}
} else {
StringWriter out = new StringWriter();
res.put("Status", "ObjectdoesntExists");
System.out.println("ver ObjectdoesntExists");
res.writeJSONString(out);
response.getOutputStream().println(out.toString());
}
} else {// id is null
StringWriter out = new StringWriter();
res.put("Status", "falseIdNUll");
System.out.println("ver falseIdNUll");
res.writeJSONString(out);
response.getOutputStream().println(out.toString());
}
} catch (Exception e) {
e.printStackTrace();
StringWriter out = new StringWriter();
res.put("Status", "false");
System.out.println("ver false");
res.writeJSONString(out);
response.getOutputStream().println(out.toString());
}
}
and:
public static void SendMail(String to, int typeOfMessage, String UserID) {
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("adress"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
/*
* all the type of messages
*/
if (typeOfMessage == 1) {
message.setSubject("title");
message.setText("text");
}else if (typeOfMessage == 2){
message.setSubject("title");
message.setText("text");
}else if (typeOfMessage == 3){
message.setSubject("title");
message.setText("text");
}else if (typeOfMessage == 4){
message.setSubject("title");
message.setText("text");
}
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
so, somebody has an idea how to avoid that problem.
more specific , to send the mail via the server but after that, I sent the response somehow to the android client, so he doesn't have to wait for 25 seconds.
thanks
Your android app should send the request in a separate thread, because sending it through the main thread will block the GUI of your app. The Tomcat-Server handles requests in different threads by default. Thus you need not starting separate threads inside of the request handling. You can start a new thread like this (see docs for java.lang.Thread):
Thread theThread = new Thread(new Runnable() {
#Override
public void run() {
// send the request to the tomcat server
}
});
theThread.start();

cannot run .jar file

I am trying to make a jar file from the following code:
public class Main {
public static void main(String[] args) {
boolean net = true;
int num = 0;
do {
if (netIsAvailable()) {
webCapture();
mailSend();
net = false;
}
} while (net);
System.exit(0);
}
public static void webCapture() {
// get default webcam and open it
Webcam webcam = Webcam.getDefault();
webcam.setViewSize(new Dimension(640, 480));
// creates test2.jpg
WebcamUtils.capture(webcam, "test2", "jpg");
}
private static boolean netIsAvailable() {
try {
final URL url = new URL("http://www.google.com");
final URLConnection conn = url.openConnection();
conn.connect();
return true;
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
return false;
}
}
public static void mailSend() {
final String username = "javaMailTest002#gmail.com";
final String password = "anaaremere";
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);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("alindradici#gmail.com"));
message.setSubject("Your computer has been accessed");
message.setText("Congratulation!");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String file = "C:\\Fast\\JDBCDemoApp\\webCamSpy\\test2.jpg";
String fileName = "attachmentName";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("done, email sent ok");
} catch (Exception e) {
System.out.println("Email sending problems");
e.printStackTrace();
}
}
}
Works fine,compiles and runs without problems,but when i do:
File | Project Structure | Artifacts click the plus icon and create new artifact choose --> jar --> From modules with dependencies.
Build | Build artifacts
and when i try to run the new created jar file I get the error:a jni error has occurred please check your installation and try again . Any idea how to solve this?
What are you doing to run the jar?
From command-line: java -jar name_of_your_created.jar

user is receiving same email twice in java

I am using the code below to send emails using java ,my project is running on a tomcat server.
the problem that user is receiving same email twice.
after some research it seems that java is sending email twice,any one can help me how I handle it?
Properties props;
Session session;
try {
props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "....");
props.put("mail.smtp.port", "25");
props.put("mail.smtp.connectiontimeout", "2000");
props.put("mail.smtp.timeout", "2000");
props.setProperty("charset", "utf-8");
session = Session.getInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
// session.setDebug(true);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
if (!to.equals("") && to != null) {
String[] toArray = to.split(";");
InternetAddress[] toList = new InternetAddress[toArray.length];
for (int i = 0; i < toArray.length; i++) {
toList[i] = new InternetAddress(toArray[i]);
}
message.addRecipients(Message.RecipientType.TO, toList);
}
if (!cc.equals("") && cc != null) {
String[] ccArray = cc.split(";");
InternetAddress[] ccList = new InternetAddress[ccArray.length];
for (int i = 0; i < ccArray.length; i++) {
ccList[i] = new InternetAddress(ccArray[i]);
}
message.addRecipients(Message.RecipientType.CC, ccList);
}
message.setSubject(subject);
//message.setText(emailBody);
message.setContent(emailBody, "text/html; charset=utf-8");
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
A way to solve errors when sending an email and, moreover, when you want to do something that has been already done from someone else, is by using a library. Open source libraries are used from a lot of developers and their bugs are all the times less than a custom source code. I would suggest you to use Apache commons Email Library.
Using this link you can find a lot of examples.

How to check whether the email account is valid?

I have already written code to check the email account it is working for gmail & yahoo mail
but it is not working for hotmail & AOL. Below is the code I have used. If any idea please help.
I am getting following exception when I pass hotmail account:
javax.mail.MessagingException: Exception reading response;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
Code:
public boolean checkEmailAccountInfo(final String userMailID,
final String password, String outgoingMailServer, String portNo) {
try {
Properties p = new Properties();
// Boolean b = new Boolean(true);
p.put("mail.smtps.auth", true);
p.put("mail.smtp.user", userMailID);
p.put("mail.smtp.host", outgoingMailServer);
p.put("mail.smtp.port", portNo);
p.put("mail.smtp.starttls.enable", true);
p.put("mail.smtp.auth", "true");
p.put("mail.smtp.8BITMIME", "true");
p.put("mail.smtp.PIPELINING", "true");
p.put("mail.smtp.socketFactory.port", 465);
p.put("mail.smtp.debug", "true");
p.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
p.put("mail.smtp.socketFactory.fallback", "false");
// create some properties and get the default Session
javax.mail.Session session = javax.mail.Session.getInstance(p,
new javax.mail.Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userMailID,
password);
}
});
session.setDebug(false);
Transport t = session.getTransport("smtp");
t.connect();
boolean isConnected = t.isConnected();
if (isConnected) {
t.close();
return true;
}
return false;
} catch (Exception e) {
return false;
}
}
You can try for this :
p.put("mail.smtp.socketFactory.port", portNo);
This will work .I have tested it with other mail ids.

Categories