I have created a java program for sending mail and I import some package that is related to the program. I have downloded package javax.mail and javax.activation and put it in to the C:\Program Files\Java\jdk1.7.0\jre\lib\ext
I compile my program then it compiles but when I run it throws Exception.
I am not able to understand why it is throwing exception.
my code is here.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.net.*;
public class SendEmail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "rs.89.rj#gmail.com";
// Sender's email ID needs to be mentioned
String from = "manoj1990gupta#yahoo.in";
try{
// Assuming you are sending email from localhost
String host = InetAddress.getLocalHost().toString();
// 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();
}}catch(Exception e){}
}
}
You need to download JavaMail API package and put it into the classpath, but make sure to include mail.jar and all dependant libraries that you can find into the lib folder.
To set the classpath from the command line :
java -cp "mail.jar;lib/*" SendEMail
Related
I'm trying to send an email using java.
This is my code.
All my credentials are correct but still I get this error.
I have seen many solutions which says turn on less secure apps but that feature is now disabled by google.
so how do I solve it.
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 = "sender#gmail.com";
// Sender's email ID needs to be mentioned
String from = "receiver#gmail.com";
// 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.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// Get the Session object.// and pass username and password
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("receiver#gmail.com", "password");
}
});
// Used to debug SMTP issues
session.setDebug(true);
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");
System.out.println("sending...");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
This is the error I'm getting.
my error in vs code
Since the less secure app feature is removed we have to follow these below steps to use Gmail via third party software that is App password
Step 1: setup 2-Step Verification:- Google Account -> Security -> 2-Step Verification -> Input password as asked -> Turn ON (you could use SMS to get Gmail code to activate 2-Step Verification)
Step 2: Generate app secret:- Google Account -> Security -> App password -> Input password as asked -> Select the app and device... -> e.g. Other(Java application) -> Input app name e.g. MyApp -> Generate
Step 3: Use generated app secret:- Copy a 16-character password
Use a 16-character password (instead of actual password) with Gmail username in your application
This should save your day
This is the code of the class Mail (there are a main inside but for the simple reason that in this way it seem to be simple to solve this problem):
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;
import java.util.Properties;
public class Mail {
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 = "mail";
String psw = "password";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtps.host", host);
properties.setProperty("mail.user", from);
properties.setProperty("mail.password", psw);
// 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();
}
}
}
And this is the terminal i see after the running:
Exception in thread "main" java.lang.NoClassDefFoundError: javax/activation/DataSource
at Mail.main(Mail.java:35)
Caused by: java.lang.ClassNotFoundException: javax.activation.DataSource
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
... 1 more
Process finished with exit code 1
The error is on :
MimeMessage message = new MimeMessage(session);
You either need to tell JDK 9 to expose the included-but-hidden java.activation module, or you need to include the JavaBeans Activation Framework (JAF; javax.activation) jar file in your project explicitly.
Do the former by adding --add-modules java.activation to your java command line.
The latter can be done by using this Maven dependency:
<dependency>
<groupId>com.sun.activation</groupId>
<artifactId>javax.activation</artifactId>
<version>1.2.0</version>
</dependency>
Try the code below
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;
import java.util.Properties;
public class MailTest {
public static void main(String [] args) {
// Recipient's email ID needs to be mentioned.
String to = "tomail";
// Sender's email ID needs to be mentioned
String from = "frommail";
String psw = "password";
// different mail will have different host name, I have implemented using gmail
String host = "smtp.gmail.com";
String port = "587";
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
// props.put("mail.smtp.connectiontimeout", timeout);
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
// Get the default Session object.
//Session session = Session.getDefaultInstance(props);
Session session = Session.getInstance(props, new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(from, psw);
}
});
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();
}
}
}
we have an Exchange Server and i wanted to test sending a mail with it. But somehow i always get the error:
com.sun.mail.smtp.SMTPSendFailedException: 550 5.7.1 Message rejected as spam by Content Filtering.
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1889)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1120)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at Test.sendMailJava(Test.java:89)
at Test.main(Test.java:29)
i tried looking at our exchange if anonymous users were allowed and they are, our Printer also send Mails without any authentification.
Here is my Java code, hope someone can help:
import java.net.URI;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.simplejavamail.email.Email;
import org.simplejavamail.mailer.Mailer;
import org.simplejavamail.mailer.config.ProxyConfig;
import org.simplejavamail.mailer.config.ServerConfig;
import org.simplejavamail.util.ConfigLoader;
public class Test {
public static void main(String[] args) {
//// // TODO Auto-generated method stub
sendMailJava();
}
public static void sendMailJava()
{
String to = "Recipient"
// Sender's email ID needs to be mentioned
String from = "Sender";
// Assuming you are sending email from localhost
String host = "Server Ip-Adress";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "25");
properties.setProperty("mail.imap.auth.plain.disable","true");
properties.setProperty("mail.debug", "true");
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("Subject");
// Now set the actual message
message.setContent("Content", "text/html; charset=utf-8");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
I also tried SimpleMail, but there is the same error.
The Connection to the smtp Server seems to work, but the message cannot be send, cause of the error above. What could it be?
Greetings,
Kevin
Edit:
i found my error, i don't know why our printers can send maisl without errors but it seems i had to whitelist my ip at our exchange server. Code was completely fine.
thanks for the help
I know you are wanting the smtp option, but I have a feeling the issue is how your server is setup and not in your code. If you get the EWS-Java Api, you can log into your exchange server directly and grab mail that way. Below is the code that would make that work:
public class ExchangeConnection {
private final ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); // change to whatever server you are running, though 2010_SP2 is the most recent version the Api supports
public ExchangeConnection(String username, String password) {
try {
service.setCredentials(new WebCredentials(username, password));
service.setUrl(new URI("https://(your webmail address)/ews/exchange.asmx"));
}
catch (Exception e) { e.printStackTrace(); }
}
public boolean sendEmail(String subject, String message, List<String> recipients, List<String> filesNames) {
try {
EmailMessage email = new EmailMessage(service);
email.setSubject(subject);
email.setBody(new MessageBody(message));
for (String fileName : fileNames) email.getAttachments().addFileAttachment(fileName);
for (String recipient : recipients) email.getToRecipients().add(recipient);
email.sendAndSaveCopy();
return true;
}
catch (Exception e) { e.printStackTrace(); return false; }
}
}
In your code you just have to create the class, then use the sendEmail method to send emails to whomever.
Your JavaMail code is not authenticating to your server, which may be why the server is rejecting the message with that error message. (Spammers often use open email servers.)
Change your code to call the Transport.send method that accepts a user name and password.
Can any one help me with a java code where i want that my html code to be added in body of the mail and the mail client should pop up so that a person can enter the To: and can edit the body if needed.
I have tried this code but this one just sends the mail.What i want is the my mail client should popup with body already entered.
package you;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
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;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
public class test1 {
public void fnSendMail(String Status) throws IOException, InvalidFormatException, URISyntaxException {
String htmlContent = null;
if (Status.equals("Completed")) {
htmlContent = "<html><br>Below is Test Execution Report.<br>Please find the attached for Detailed Results"
+ "<br><br><table border='1' cellpadding='2' cellspacing='3' width='40%' bordercolor='#999999' style='border-collapse: collapse;'>"
+ "<tr><th>SNo</th><th>Run_Method</th><th>abc_name</th><th>Execution_Status</th></tr>" + "</table>"
+ "<br><br><br><h3 style='color:FireBrick;'>Please do not respond to this mail </h3></html>";
} else {
htmlContent = "<html><br>" + "<h3 style='color:FireBrick;'>Automation got failed due to some issue, hence "
+ "Please verify Maven Errors.<br><br>Execution Status till failure is attached.</h3></html>";
}
String from = "abc#cdf.com";
String host = "x.y.z";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
Multipart multipart = new MimeMultipart();
BodyPart messageBodyText = new MimeBodyPart();
message.setSubject("CSI API Automated Testing Report is " + Status);
messageBodyText.setContent(htmlContent, "text/html");
multipart.addBodyPart(messageBodyText);
message.setContent(multipart);
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
public static void main(String[] args) {
test1 test2= new test1();
try {
test2.fnSendMail("Completed");
System.out.println("Email sent.");
} catch (Exception ex) {
System.out.println("Failed to sent email.");
ex.printStackTrace();
}
}
}
Any other way to do this will also work, but i need is java and javascript only
Instead of calling Transport.send you have to call MimeMessage.saveChanges then use MimeMessage.writeTo to save it to the filesystem as '.eml'. Then open that file with java.awt.Desktop.open to launch the email client. Your system must have a mime association with eml or the open call will fail.
If the O/S mime type for eml is not set to something like outlook.exe /eml %1 then you might have to resort to using the process API to launch outlook directly using the eml switch. For example, if you want to preview the foo.eml draft message then the command would be:
outlook.exe /eml foo.eml
You'll have to handle clean up after the email client is closed.
You also have to think about the security implications of email messages being left on the file system.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you send email from a Java app using Gmail?
How do I send an SMTP Message from Java?
Here's an example for Gmail smtp:
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.mail.internet.*;
import com.sun.mail.smtp.*;
public class Distribution {
public static void main(String args[]) throws Exception {
Properties props = System.getProperties();
props.put("mail.smtps.host","smtp.gmail.com");
props.put("mail.smtps.auth","true");
Session session = Session.getInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("mail#tovare.com"));;
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("tov.are.jacobsen#iss.no", false));
msg.setSubject("Heisann "+System.currentTimeMillis());
msg.setText("Med vennlig hilsennTov Are Jacobsen");
msg.setHeader("X-Mailer", "Tov Are's program");
msg.setSentDate(new Date());
SMTPTransport t =
(SMTPTransport)session.getTransport("smtps");
t.connect("smtp.gmail.com", "admin#tovare.com", "<insert password here>");
t.sendMessage(msg, msg.getAllRecipients());
System.out.println("Response: " + t.getLastServerResponse());
t.close();
}
}
Now, do it this way only if you would like to keep your project dependencies to a minimum, otherwise i can warmly recommend using classes from apache
http://commons.apache.org/email/
Regards
Tov Are Jacobsen
Another way is to use aspirin (https://github.com/masukomi/aspirin) like this:
MailQue.queMail(MimeMessage message)
..after having constructed your mimemessage as above.
Aspirin is an smtp 'server' so you don't have to configure it. But note that sending email to a broad set of recipients isnt as simple as it appears because of the many different spam filtering rules receiving mail servers and client applications apply.
Please see this post
How can I send an email by Java application using GMail, Yahoo, or Hotmail?
It is specific to gmail but you can substitute your smtp credentials.
See the following tutorial at Java Practices.
http://www.javapractices.com/topic/TopicAction.do?Id=144
See the JavaMail API and associated javadocs.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public void postMail(String recipients[], String subject,
String message , String from) throws MessagingException {
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.jcom.net");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(false);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Optional : You can also set your custom headers in the Email if you Want
msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}