i'm getting some problems with the "session" object while trying to send an Email, that's the code
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class EmailSender {
private String user;
private String password;
private String host;
private String destinatario;
private String oggetto;
private String allegato;
/**
*
* Costruttore completo, richiede i parametri
* di connessione al server di posta
* #param user
* #param password
* #param host
* #param mittente
* #param destinatari
* #param oggetto
* #param allegati
*/
public EmailSender(String user, String password, String host,
String destinatario,
String oggetto){
this.user = user;
this.password = password;
this.host = host;
this.destinatario = destinatario;
this.oggetto = oggetto;
}
// Metodo che si occupa dell'invio effettivo della mail
public void inviaEmail() {
int port = 465; //porta 25 per non usare SSL
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.user", user);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
// commentare la riga seguente per non usare SSL
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.socketFactory.port", port);
// commentare la riga seguente per non usare SSL
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getInstance(props, null);
session.setDebug(true);
// Creazione delle BodyParts del messaggio
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
try{
// COSTRUZIONE DEL MESSAGGIO
Multipart multipart = new MimeMultipart();
MimeMessage msg = new MimeMessage(session);
// header del messaggio
msg.setSubject(oggetto);
msg.setSentDate(new Date());
msg.setFrom(new InternetAddress(user));
// destinatario
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(destinatario));
// corpo del messaggio
messageBodyPart1.setText("Ciao sono veramente euforico");
multipart.addBodyPart(messageBodyPart1);
// allegato al messaggio
allegato = CreazioneFile.AggiungiDati();
DataSource source = new FileDataSource(allegato);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(allegato);
multipart.addBodyPart(messageBodyPart2);
// inserimento delle parti nel messaggio
msg.setContent(multipart);
Transport transport = session.getTransport("smtps"); //("smtp") per non usare SSL
transport.connect(host, user, password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
System.out.println("Invio dell'email Terminato");
}catch(AddressException ae) {
ae.printStackTrace();
}catch(NoSuchProviderException nspe){
nspe.printStackTrace();
}catch(MessagingException me){
me.printStackTrace();
}
}
}
An that's the Test Class:
import java.io.File;
public class TestEmail {
public static void main(String[] args) {
File allegato = new File(CreazioneFile.AggiungiDati());
EmailSender email = new EmailSender(
"myuser",
"mypass",
"smtp.gmail.com",
"sendToAddress",
"Invio automatico email da Java"
);
email.inviaEmail();
System.out.println(allegato);
allegato.delete();
}
}
That's the stack error:
Exception in thread "main" java.lang.NoClassDefFoundError: com.sun.mail.util.MailLogger
at javax.mail.Session.initLogger(Session.java:226)
at javax.mail.Session.(Session.java:210)
at javax.mail.Session.getDefaultInstance(Session.java:321)
The problem it's for sure about RAD and session,but i dont know where i've to set, and what i've to set, can u please help me?
com.sun.mail.util.MailLogger is part of JavaMail API. It is already included in EE environment (that's why you can use it on your live server), but it is not included in SE environment.
The JavaMail API is available as an optional package for use with Java SE platform and is also included in the Java EE platform.
99% that you run your tests in SE environment which means what you have to bother about adding it manually to your classpath when running tests.
Hope below link will helpful for you
http://crunchify.com/java-mailapi-example-send-an-email-via-gmail-smtp/
Related
Following code sample found in:
https://www.codejava.net/java-ee/javamail/embedding-images-into-e-mail-with-javamail
The images are attached to the email, but not embedded in the html of the email.
package net.codejava.mail;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
/**
* This utility class provides a functionality to send an HTML e-mail message
* with embedded images.
* #author www.codejava.net
*
*/
public class EmbeddedImageEmailUtil {
/**
* Sends an HTML e-mail with inline images.
* #param host SMTP host
* #param port SMTP port
* #param userName e-mail address of the sender's account
* #param password password of the sender's account
* #param toAddress e-mail address of the recipient
* #param subject e-mail subject
* #param htmlBody e-mail content with HTML tags
* #param mapInlineImages
* key: Content-ID
* value: path of the image file
* #throws AddressException
* #throws MessagingException
*/
public static void send(String host, String port,
final String userName, final String password, String toAddress,
String subject, String htmlBody,
Map<String, String> mapInlineImages)
throws AddressException, MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
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.user", userName);
properties.put("mail.password", password);
// 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());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(htmlBody, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds inline image attachments
if (mapInlineImages != null && mapInlineImages.size() > 0) {
Set<String> setImageID = mapInlineImages.keySet();
for (String contentId : setImageID) {
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.setHeader("Content-ID", "<" + contentId + ">");
imagePart.setDisposition(MimeBodyPart.INLINE);
String imageFilePath = mapInlineImages.get(contentId);
try {
imagePart.attachFile(imageFilePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(imagePart);
}
}
msg.setContent(multipart);
Transport.send(msg);
}
}
package net.codejava.mail;
import java.util.HashMap;
import java.util.Map;
/**
* This program tests out the EmbeddedImageEmailUtil utility class.
* #author www.codejava.net
*
*/
public class InlineImageEmailTester {
/**
* main entry of the program
*/
public static void main(String[] args) {
// SMTP info
String host = "smtp.gmail.com";
String port = "587";
String mailFrom = "YOUR_EMAIL";
String password = "YOUR_PASSWORD";
// message info
String mailTo = "YOUR_RECIPIENT";
String subject = "Test e-mail with inline images";
StringBuffer body
= new StringBuffer("<html>This message contains two inline images.<br>");
body.append("The first image is a chart:<br>");
body.append("<img src=\"cid:image1\" width=\"30%\" height=\"30%\" /><br>");
body.append("The second one is a cube:<br>");
body.append("<img src=\"cid:image2\" width=\"15%\" height=\"15%\" /><br>");
body.append("End of message.");
body.append("</html>");
// inline images
Map<String, String> inlineImages = new HashMap<String, String>();
inlineImages.put("image1", "E:/Test/chart.png");
inlineImages.put("image2", "E:/Test/cube.jpg");
try {
EmbeddedImageEmailUtil.send(host, port, mailFrom, password, mailTo,
subject, body.toString(), inlineImages);
System.out.println("Email sent.");
} catch (Exception ex) {
System.out.println("Could not send email.");
ex.printStackTrace();
}
}
}
Any comments will be very appreciated.
Problem solved.
I have to change:
new MimeMultipart();
to this:
new MimeMultipart("related");
I want to send a mail from my email address to another email address via clicking a button in JFrame netbeans.Here is the code,
import java.awt.HeadlessException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
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 javax.swing.JOptionPane;
import com.sun.mail.util.MailSSLSocketFactory;
import java.io.File;
import javax.mail.PasswordAuthentication;
import javax.mail.*;
import javax.swing.JFileChooser;
private void btn_sendActionPerformed(java.awt.event.ActionEvent evt) {
final String From = txt_from.getText();
final String password = txt_password.getText();
String To = txt_to.getText();
String subject = txt_sub.getText();
String txtmessage = txt_body.getText();
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "587");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLsocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.fallback", "true");
props.put("mail.smtp.ssl.socketFactory", "true");
props.put("mail.smtp.EnableSSL.enable","true");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(From, password);
}
}
);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(From));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(To));
message.setSubject(subject);
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(txtmessage);
Multipart multiPart = new MimeMultipart();
multiPart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachment_path);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(txt_DocAttach.getText());
multiPart.addBodyPart(messageBodyPart);
message.setContent(multiPart);
Transport.send(message);
JOptionPane.showMessageDialog(rootPane, "Message is sent");
} catch (MessagingException | HeadlessException e) {
JOptionPane.showMessageDialog(rootPane, e);
}
}
But it is giving me following error,
javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: java.io.lOException: Exception in startTLS using SSL socket factory class null: host, port smtp.gmail.com, 587; Exception: java.lang.ClassNotFoundException: javax.netssl.SSLsocketFactory
Tried a lot but can't figure out what to do to solve it? Help please.
Try to change the value of the property mail.smtp.socketFactory.class
to javax.net.ssl.SSLSocketFactory instead of javax.net.ssl.SSLsocketFactory,
The class name is case sensitive.
For more infromations about connection properties you can look at:
Where to find all available Java mail properties?
As others have pointed out, your socket factory settings were wrong.
More importantly, you never needed to set them at all!
This error can also pop up if your JavaMail lib (mail.jar or javax.mail.jar) is too old.
Download the newest version from here: https://javaee.github.io/javamail/
Error 1:
Description Resource Path Location Type The project was not built
since its build path is incomplete. Cannot find the class file for
java.util.Map$Entry. Fix the build path then try building this project
EmailSendingWebApp Unknown Java Problem
error 2 :
Description Resource Path Location Type The type java.util.Map$Entry
cannot be resolved. It is indirectly referenced from required .class
files EmailUtility.java /EmailSendingWebApp/src/net/codejava/email
line 29 Java Problem
This is my code:
code 1 : package net.codejava.email;
import java.util.Date;
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;
/**
* A utility class for sending e-mail messages
* #author www.codejava.net
*
*/
public class EmailUtility {
public static void sendEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) throws AddressException,
MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
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");
// 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());
msg.setText(message);
// sends the e-mail
Transport.send(msg);
}
}
code 2 :
package net.codejava.email;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* A servlet that takes message details from user and send it as a new e-mail
* through an SMTP server.
*
* #author www.codejava.net
*
*/
#WebServlet("/EmailSendingServlet")
public class EmailSendingServlet extends HttpServlet {
private String host;
private String port;
private String user;
private String pass;
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
host = context.getInitParameter("host");
port = context.getInitParameter("port");
user = context.getInitParameter("user");
pass = context.getInitParameter("pass");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// reads form fields
String recipient = request.getParameter("recipient");
String subject = request.getParameter("subject");
String content = request.getParameter("content");
String resultMessage = "";
try {
EmailUtility.sendEmail(host, port, user, pass, recipient, subject,
content);
resultMessage = "The e-mail was sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
} finally {
request.setAttribute("Message", resultMessage);
getServletContext().getRequestDispatcher("/Result.jsp").forward(
request, response);
}
}
}
I am new to eclipse so I don't know how to link these two files, please help. Thanks.
Eclipse can compile Java projects against different installed JREs. Unless care is taken, the project's reference to its JRE is not portable. Verify that your Installed JREs preference page is pointing to something valid, then edit the project's Java Build Path so that it's referring to a valid JRE.
http://help.eclipse.org/neon/topic/org.eclipse.jdt.doc.user/reference/preferences/java/debug/ref-installed_jres.htm
http://help.eclipse.org/neon/topic/org.eclipse.jdt.doc.user/reference/ref-properties-build-path.htm?cp=1_4_3_1
In this example Im trying to send an attachment via mail using gmail smtp server.
Mailer.java
package com.servlet.mail;
import java.io.File;
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.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
public class Mailer {
public static void send(String to ,String subject ,String msg)
{
System.out.println("in Mailer class");
final String user="sup.ni#gmail.com";
final String psw="XXXXXX";//changes to be made accoordingly
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(user,psw);
}
});
try
{
System.out.println(to+""+subject+""+msg);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
//message.setText(msg);
//Mail sending with attachement
BodyPart msgBodyPart1 = new MimeBodyPart();
msgBodyPart1.setText("This is message body");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(msgBodyPart1);
MimeBodyPart msgBodyPart2 = new MimeBodyPart();
String path = "D:/Self_Learning/Servlets/Servlet_Examples/WebContent/CSS/";
String filename= path+"Note.txt";
System.out.println(path);
message.setHeader("Content-Disposition", "attachement ; filename= \""+filename+"\"");
DataSource src = new FileDataSource(filename);
msgBodyPart2.setDataHandler(new DataHandler(src));
msgBodyPart2.setFileName(path);
multipart.addBodyPart(msgBodyPart2);
message.setContent(multipart);
//SEND MSG
Transport.send(message);
System.out.println("Mail sent successfully");
}
catch(MessagingException e)
{
System.out.println(e);
}
}
}
The requirement is that I want the attachment name to be just the file name.
Here in this example when I check the mail the attachment will have absolute path.
This is the file-name I receive in the attached file "D:/Self_Learning/Servlets/Servlet_Examples/WebContent/CSS/Note.txt"
But I want the attached file to be just Note.txt
Please let me know what is changes has to be done in order to get my required output
You're setting the filename in the header using the filename= \".....\" key-value pair. Just change this value to the name you want to set.
For example:
String path = "D:/Self_Learning/Servlets/Servlet_Examples/WebContent/CSS/";
String name = "Note.txt";
String filename= path+name;
message.setHeader("Content-Disposition", "attachement ; filename= \""+name+"\"");
I am using a program to send emails. The code works when I use some other mail server. but I need to use my company's email account to send email. And the email account is provided by gmail xxxx#companyname.com. When I change the mail host to `stmp.gmail.com, I encounter the following error:
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. st6sm11092256pbc.58
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1515)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1054)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:634)
at javax.mail.Transport.send0(Transport.java:189)
at javax.mail.Transport.send(Transport.java:118)
at Mail.sendMail(Mail.java:48)
at Test.main(Test.java:6)
The code is as follows
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class Email_Autherticator extends Authenticator {
String username = "xxxx#gmail";
String password = "xxxxx";
public Email_Autherticator() {
super();
}
public Email_Autherticator(String user,String pwd){
super();
username = user;
password = pwd;
}
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username,password);
}
}
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Mail {
private String host = "smtp.gmail.com";
private String mail_head_name = "this is head of this mail";
private String mail_head_value = "this is head of this mail";
private String mail_to = "xxxx#gmail.com";
private String mail_from = "xxxx#Comanyname.com";//using gmail server
private String mail_subject = "this is the subject of this test mail";
private String mail_body = "this is mail_body of this test mail";
private String personalName = "xxx";
public void sendMail() throws SendFailedException{
try {
Properties props = new Properties();
Authenticator auth = new Email_Autherticator();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
System.out.println(props);
Session session = Session.getDefaultInstance(props,auth);
MimeMessage message = new MimeMessage(session);
message.setContent("Hello","text/plain");
message.setSubject(mail_subject);
message.setText(mail_body);
message.setHeader(mail_head_name, mail_head_value);
message.setSentDate(new Date());
Address address = new InternetAddress(mail_from,personalName);
message.setFrom(address);
Address toaddress = new InternetAddress(mail_to);
message.addRecipient(Message.RecipientType.TO,toaddress);
System.out.println(message);
Transport.send(message);
System.out.println("Send Mail Ok!");
} catch (Exception e) {
e.printStackTrace();
}
//return flag;
}
}
You almost certainly just need to rework your code to add the properties defined in the JavaMail API - Sending email via Gmail SMTP example example.
You can probably get away with setting your props to this:
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.setProperty("mail.smtp.user", gmailUsername);
properties.setProperty("mail.smtp.password", gmailPassword);
As this seems to be for work--if you can--I suggest using Spring. It makes it a lot cleaner and easier to use. I just recently did something similar to this with Spring and Gmail SMTP.
You need to define below properties in your java code.
import below package
import java.util.Properties;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
and add following to your code:
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
Use javax.mail.authenticator to authenticate with gmail servers
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Try this should work for you.
If still having issues, refer this error doc:
https://pepipost.com/tutorials/common-javamail-smtp-errors/
for sending SMTP email using javaMail API