This question already has answers here:
"Error: Main method not found in class MyClass, please define the main method as..."
(10 answers)
Closed 9 years ago.
I'm trying to mail from Java.
I'm getting this runtime exception:
java.lang.NoSuchMethodError: main. Exception in thread "main"
Cant figure out what the problem is. Please help.
I'm using the following code:
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 Mail{
public static void Mail(String from, String to, String subject, String text)
{
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
Session mailSession = Session.getDefaultInstance(props, null);
Message simpleMessage = new MimeMessage(mailSession);
InternetAddress fromAddress = null;
InternetAddress toAddress = null;
try
{
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
} catch (AddressException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
Transport.send(simpleMessage);
} catch (MessagingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args)
{
String from = "prav.br#gmail.com";
String to = "prav.br#gmail.com";
String subject = "Test";
String message = "A test message";
Mail.Mail(from, to, subject, message);
}
}
I don't see any problem in code[atleast it should run] . make sure mail api is in classpath to compile.
Suggestion : your code doesn't follow java standard naming convention you should follow that.
Also See:
Coding Convention
Having removed all the JavaMail code from your sample, it compiles and runs with no problems. Having a static method with the same name as the class is definitely unconventional and I would advise against it, but it should work...
You haven't given us any details or your build or execution environment. Please do so, and provide a short but complete program which demonstrates the problem - I suggest you get rid of all hints of JavaMail as that shouldn't be involved here.
You have to create method main(String[] args)
Your method is called Main instead of main.
It accepts several arguments instead of 1 String[]
BTW java naming conventions requires calling methods using small letters.
Related
This question already has answers here:
How can I solve "java.lang.NoClassDefFoundError"?
(34 answers)
JAVA: MAIL: How can i solve ClassNotFoundException : javax.mail.internet.AddressException?
(1 answer)
Closed 2 years ago.
I keep getting this same error message every time i try to run my code and im just lost on whats wrong with it. This is my first time trying to write code that will send a email using java via Gmail, here is the error code i keep receiving:
Exception in thread "main" java.lang.NoClassDefFoundError: javax/mail/Authenticator
at emailTest.javaMail.main(javaMail.java:5)
Caused by: java.lang.ClassNotFoundException: javax.mail.Authenticator
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 1 more
iv tried looking up for videos online to help me solve the proble, but its really hard since i dont really know what the problem is.
Here is my code:
JavaMailUtil.Java:
package emailTest;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class JavaMailUtil {
public static void sendMail(String recepient) throws Exception {
System.out.println("preping to send email");
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.sntp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
String myAccountEmail = "removed_for_obvious_reasons;
String myAccountPass = "removed_for_obvious_reasons";
Session session = Session.getInstance(properties, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(myAccountEmail, myAccountPass);
}
});
Message message = prepareMessage(session, myAccountEmail, recepient);
Transport.send(message);
System.out.println("Message sent succesfully.");
}
private static Message prepareMessage(Session session, String myAccountEmail, String recepient) {
Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress("myAccountEmail"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recepient));
message.setSubject("My first email from java");
message.setText("Hey There, \n Look at my Email");
return message;
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
and here is javaMail.java (contains main method to run):
package emailTest;
public class javaMail {
public static void main(String[] args) throws Exception {
JavaMailUtil.sendMail("removed_for_obvious_reasons_acc2");
}
}
im 100% sure im typing in the senders email and password correct too.
Try using this:
public static void main(String[] args) {
String contentText = "";
String mailWrapper = "";
// Recipient's email ID needs to be mentioned.
final String to = "some#gmail.com";
// Sender's email ID needs to be mentioned
final String from = "to#gmail.com";
String password = "pasword";
// 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.debug", "false");
// Get the Session object.// and pass username and password
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
// Used to debug SMTP issues
session.setDebug(false);
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("Your Subject goes here");
// Now set the actual message
message.setText("This is actual message");
System.out.println("SENDING MAIL...");
// Send message
Transport.send(message);
System.out.println("EMAIL SENT SUCCESSFULLY.");
} catch (MessagingException mex) {
System.out.println("ERROR IN SENDING EMAIL");
}
}
This question already has answers here:
Java 8 Lambda function that throws exception?
(27 answers)
Closed 6 years ago.
I have the following code snippet.
package web_xtra_klasa.utils;
import java.util.Arrays;
import java.util.Properties;
import java.util.function.Function;
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 Main {
public static void main(String[] args) throws Exception {
Transport transport = null;
try {
final Properties properties = new Properties();
final Session session = Session.getDefaultInstance(properties, null);
final MimeMessage message = new MimeMessage(session);
final String[] bcc = Arrays.asList("user#example.com").stream().toArray(String[]::new);
message.setRecipients(Message.RecipientType.BCC, Arrays.stream(bcc).map(InternetAddress::new).toArray(InternetAddress[]::new));
} finally {
if (transport != null) {
try {
transport.close();
} catch (final MessagingException e) {
throw new RuntimeException(e);
}
}
}
}
}
This does not compile because of the following error.
Unhandled exception type AddressException
I have researched a little and all the solutions were only with wrapping the checked exception in a runtime exception in a custom method. I want to avoid writing additional code for that stuff. Is there any standard way to handle such cases?
EDIT:
What I have done so far is
message.setRecipients(Message.RecipientType.BCC,
Arrays.stream(bcc).map(e -> {
try {
return new InternetAddress(e);
} catch (final AddressException exc) {
throw new RuntimeException(e);
}
}).toArray(InternetAddress[]::new));
but it does not look nice. I could swear that in one of the tutorials I have seen something standard with rethrow or something similar.
You might use some Try<T> container.
There are several already written implementations. For example:
https://github.com/javaslang/javaslang/blob/master/javaslang/src/main/java/javaslang/control/Try.java
https://github.com/hiro0107/java8-try-monad/blob/master/src/main/java/com/github/hiro0107/trymonad/Try.java
Or you can write it yourself.
This question already has answers here:
Gmail as JavaMail SMTP server
(1 answer)
How can I send an email by Java application using GMail, Yahoo, or Hotmail?
(14 answers)
Closed 7 years ago.
I'm new in Java world and trying to create a small app to send email to my gmail account. But I am getting some error which I tried to solve, but failed. My full code is the following:
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMyEmail {
public static void main(String[] args) throws UnsupportedEncodingException {
System.out.println("Hello");
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
String msgBody = "...";
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("tinyNina#gmail.com", "Example.com Admin"));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress("tinyNina#gmail.com", "Mr. User"));
msg.setSubject("Your Example.com account has been activated");
msg.setText(msgBody);
Transport.send(msg);
System.out.println("Done");
} catch (AddressException e) {
System.out.println(e);
// ...
} catch (MessagingException e) {
System.out.println(e);
// ...
}
And I am getting the following error:
Hello
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect
}
}
Can anybody tell me where I am doing some mistake?
Note: I tried lots of ways and then I found a google link https://cloud.google.com/appengine/docs/java/mail/ and then I tried and getting that error.
I've started to build a service monitor using SoapUI 5 (non-Pro edition). The service monitor should be able to:
Teststep1 (http Request): Call an URL, which genereates a token
Teststep2 (groovy script): Parse the response and save the token as a property
Teststep3 (http Request): Call another URL
Teststep4 (groovy script): Parse the repsonseHttpHeader, save the statusHeader in a testCase-property and check if it is '200', '400', '403'...
Teststep5 (groovy script): Write an email whenever it is not '200'
Steps 1 to 4 are working without any problems and also sending emails (step 5) by executing my script is working, but I would like to change the email content depending and the statusHeader. For example:
404: The requested resource could not be found
403 : It is forbidden. Please check the token generator
...
Code for parsing and saving httpHeaderStatusCode:
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
// get responseHeaders of ServiceTestRequest
def httpResponseHeaders = context.testCase.testSteps["FeatureServiceTestRequest"].testRequest.response.responseHeaders
// get httpResonseHeader and status-value
def httpStatus = httpResponseHeaders["#status#"]
// extract value
def httpStatusCode = (httpStatus =~ "[1-5]\\d\\d")[0]
// log httpStatusCode
log.info("HTTP status code: " + httpStatusCode)
// Save logged token-key to next test step or gloabally to testcase
testRunner.testCase.setPropertyValue("httpStatusCode", httpStatusCode)
Code for sending email:
// From http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
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 SendMailTLS {
public static void main(String[] args) {
final String username = "yourUsername#gmail.com";
final String password = "yourPassword";
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("yourSendFromAddress#domain.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("yourRecipientsAddress#domain.com"));
message.setSubject("Status alert");
message.setText("Hey there,"
+ "\n\n There is something wrong with the service. The httpStatus from the last call was: ");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
What I want to do: I want to access the testCase httpStatusCode property saved on my first groovy script (last line) in my last groovy script where I send my email. Is there something, which can handle this?
I've searched for two hours, but I have't found something useful. A possible workaround would be that I have to call different Email-Scripts with different messages using if statements and the testRunner.runTestStepByName method, but changing the content of the email would be nicer.
Thanks in advance!
You have to change your class definition in the last groovy script, instead of main define a method to send the email which has statusCode as parameter in your sendMailTLS class. Then in the same groovy script where you define your class use def statusCode = context.expand('${#TestCase#httpStatusCode}'); to get your property value and then create an instance of your class and invoke your method passing the property statusCode with:
// create new instance of your class
def mailSender = new SendMailTLS();
// send the mail passing the status code
mailSender.sendMail(statusCode);
All together in your groovy script have to look like:
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;
// define the class
class SendMailTLS {
// define a method which recive your status code
// instead of define main method
public void sendMail(String statusCode) {
final String username = "yourUsername#gmail.com";
final String password = "yourPassword";
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("yourSendFromAddress#domain.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("yourRecipientsAddress#domain.com"));
message.setSubject("Status alert");
// THERE YOU CAN USE STATUSCODE FOR EXAMPLE...
if(statusCode.equals("403")){
message.setText("Hey there,"
+ "\n\n You recive an 403...");
}else{
message.setText("Hey there,"
+ "\n\n There is something wrong with the service. The httpStatus from the last call was: ");
}
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
// get status code
def statusCode = context.expand('${#TestCase#httpStatusCode}');
// create new instance of your class
def mailSender = new SendMailTLS();
// send the mail passing the status code
mailSender.sendMail(statusCode);
I test this code and it works correctly :).
Hope this helps,
Here is what you can do:
Add a map in your java class which contains all the expected
Response codes, and Response Messages as you wanted to have either
subject or content of email.
I would suggest you to have it in a method other than main so that
you intiantiate class object and call method from soapui's groovy
script, of course you do it with main as well.
Method should take response code as argument.
Use it as key to get the relevant value from the map and put it to
email.
Create a jar file for your class and put jar file under
$SOAPUI_HOME/bin/ext directory
In your soapui test case, for test step5 (groovy) call your method
from the class you wrote like how you call in java. For example: How
to call your java from soapui groovy given below
//use package, and imports also if associated
SendMailTLS mail = new SendMailTLS()
//assuming that you move the code from main method to sendEmail method
mail.sendEmail(context.expand('${#TestCase#httpStatusCode}')
As subject is self explanatory - I am facing issue in sending email to a group email using java mail.
I have gone through through several blogs & articles which are of no help & does not have a precise answer or hangs in middle.
Can you please help. Here is my mail class for you. My mail is going to have a link to ftp location & a text file as an attachment.
To separate the issue i tried to send a simple mail to the group as well but that didn't help either.
I tried to find answers in places like java-forums.org & Stack overflow but found no luck.
I appreciate your quality time & help in providing an insight to the issue.
To explain the issue better-
My Automation framework when completes the execution of test cases, it sends a mail to me with the link to execution report & a log file as an attachment. Now the audience for the report has expanded & we need to send the mail to a group email address.
When I set the email (to say group.email#company.com) none of the users in the group receives the mail. Where as if I send the email to my email address or anyone else email address it works.
I get no logs or error for this & so I am not able to understand the issue correctly.
An insight from the experts will help in understanding the issue.
Thanks in advance.
Akshat
import java.util.ArrayList;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class ReportMail {
private MimeMessage message = null;
private Session emailSession = null;
private MimeBodyPart textPart = null;
private ArrayList<MimeBodyPart> attachmentArray = null;
public void sendMailer(String mailToId, String string, String mailServer1,
int mailPort, String mailAdmin) {
Properties mailProperties = null;
mailProperties = new Properties();
String adminEmailId = mailAdmin;
String mailServer = mailServer1;
mailProperties.put("mail.transport.protocol", "smtp");
//mailProperties.put("mail.smtp.auth", "true");
mailProperties.put("mail.smtp.host", mailServer);
mailProperties.put("mail.from", adminEmailId);
mailProperties.put("mail.smtp.port", mailPort);
mailProperties.put("mail.to", mailToId);
try {
emailSession = Session.getInstance(mailProperties);
emailSession.setDebug(false);
message = new MimeMessage(emailSession);
textPart = new MimeBodyPart();
attachmentArray = new ArrayList<MimeBodyPart>(2);
message.addRecipients(RecipientType.TO, mailToId);
message.setSubject(string);
message.setFrom(new InternetAddress(adminEmailId));
setContent("PCM Automation Report");
//setContent("test123");
sendEMail();
} catch (Exception e) {
e.printStackTrace();
}
}
public void setContent(String content) {
try {
textPart.setContent(content, "text/html");
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean sendEMail() throws Exception {
try {
Multipart mp = new MimeMultipart();
mp.addBodyPart(textPart);
for (int i = 0; i < attachmentArray.size(); i++)
mp.addBodyPart(attachmentArray.get(i));
/********************
*
*/
// Part two is attachment
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Below is the link for the Test Automation report as link & attached Log file. PFA.");
//mp.addBodyPart(messageBodyPart);
String filename = "logfile.log"; //C:\workspacePCMSanity\PCMSanity\logfile.log
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
mp.addBodyPart(messageBodyPart);
/**
*
*/
message.setContent(mp);
Transport transport = emailSession.getTransport();
transport.connect();
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return true;
}
}
In Microsoft Exchange Server there is a special group address setting option Require that all senders are authenticated. When an unknown user is used as a sender, such an email is rejected. You can either send emails in the name of real user or enable this option. In the latter case the group address is opened to spam.
http://technet.microsoft.com/en-us/library/bb124405%28v=exchg.141%29.aspx
Java doesn't know whether an email address is for a single user or a group.
Probably the issue with SMTP Server.