Javamail, error when sending attachments. - java

I am trying to send an email. When I send it without an attachment, it sends the email correctly. If I try to attach something, then it doesn't work.
The Class:
import com.sun.mail.smtp.SMTPTransport;
import java.io.File;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
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;
import javax.swing.JOptionPane;
/**
*
* #author doraemon
*/
public class GoogleMail {
public static void Send(String from, String pass, String[] to, String assunto, String mensagem, File[] anexos) {
String host = "smtp.risantaisabel.com.br";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true"); // added this line
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
//String[] to = {"tarcisioambrosio#gmail.com"}; // added this line
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InternetAddress[] toAddress = new InternetAddress[to.length];
boolean enviado = true;
// To get the array of addresses
for( int i=0; i < to.length; i++ ) { // changed from a while loop
try {
toAddress[i] = new InternetAddress(to[i]);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// System.out.println(Message.RecipientType.TO);
for( int i=0; i < toAddress.length; i++) { // changed from a while loop
try {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
message.setSubject(assunto);
//message.setContent(mensagem, "text/plain");
message.setText(mensagem);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
if(anexos.length == 0){
}
else {
Multipart mp = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
for(int i = 0; i < anexos.length;i++) {
MimeBodyPart mbp2 = new MimeBodyPart();
FileDataSource fds = new FileDataSource(anexos[i].getPath());
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
mp.addBodyPart(mbp2);
}
messageBodyPart.setContent(message, "multipart/mixed");
mp.addBodyPart(messageBodyPart);
message.setContent(mp);
}
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, "<html><b>Email não enviado, tente novamente confirmando seus dados");
enviado = false;
e.printStackTrace();
}
if(enviado) {
JOptionPane.showMessageDialog(null, "<html><b>Email enviado.</html></b> \n\n Caso tenha digitado errado o email, somente pela sua caixa de entrada poderá confirmar se chegou. \n\n<html> Email da parte digitado:<b><font size = 3 COLOR=#ff0000> " + to[0]);
}
}
}
If I change the the setContent to text/plain, I get:
javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.io.IOException: "text/html" DataContentHandler requires String object, was given object of type class javax.mail.internet.MimeMessage
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1167)
If I change the setContent to multipart/mixed, I get:
javax.mail.MessagingException: MIME part of type "multipart/mixed" contains object of type javax.mail.internet.MimeMessage instead of MimeMultipart
Do you have any idea how I can fix this? Thanks.

Remove
message.setText(mensagem);
Change
messageBodyPart.setContent(message, "multipart/mixed");
to
messageBodyPart.setText(mensagem);
and move it and the following line above the "for" loop.
Also, see this JavaMail FAQ entry of common mistakes.

Now I am able to send mail with attachment and body content using JMS API.
It worked for me putting multiple attachment files too.
final String fromAddress = formBean.getString("fromEmail");
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromAddress, formBean.getString(password));
}
});
Transport transport = null;
try {
transport = session.getTransport();
Message message = new MimeMessage(session);
String messageBody = "<div style=\"color:red;\">" + formBean.getString("mailBody") + "</div>";
message.setSentDate(new Date());
message.setSubject(formBean.getString("subject"));
// message.setContent(mensagem, "text/plain");
Multipart mp = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
String[] filesNameArray=new String[]{"C:\\Users\\karola\\Desktop\\context.xml","C:\\Users\\karola\\Desktop\\site.xml"};
for(String fileToAttached:filesNameArray){
MimeBodyPart mbp2 = new MimeBodyPart();
FileDataSource fds = new FileDataSource(new File(fileToAttached));
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
mp.addBodyPart(mbp2);
}
messageBodyPart.setText(messageBody);
mp.addBodyPart(messageBodyPart);
message.setContent(mp);
transport.connect();
message.setReplyTo(InternetAddress.parse(formBean.getString("replyTo")));
Transport.send(message, InternetAddress.parse(formBean.getString("toAddress")));
// message(RecipientType.TO,
// InternetAddress.parse(formBean.getString("toAddress")));
// transport.sendMessage(message, message.getAllRecipients());
transport.close();

Related

Java: How do I attach multiple files to an email?

I have a list of files that are created on application launch, and I want those files to be sent via email. The emails do send, but they don't have any attachments.
Here's the code:
private Multipart getAttachments() throws FileNotFoundException, MessagingException
{
File folder = new File(System.getProperty("user.dir"));
File[] fileList = folder.listFiles();
Multipart mp = new MimeMultipart("mixed");
for (File file : fileList)
{
// ext is valid, and correctly detects these files.
if (file.isFile() && StringFormatter.getFileExtension(file.getName()).equals("xls"))
{
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(file, file.getName()));
messageBodyPart.setFileName(file.getName());
mp.addBodyPart(messageBodyPart);
}
}
return mp;
}
There's no error, warning, or anything else. I even tried creating a Multipart named childPart and assigning it to mp through .setParent(), and that did not work either.
I am assigning the attachments this way:
Message msg = new MimeMessage(session);
Multipart mp = getAttachments();
msg.setContent(mp); // Whether I set it here, or next-to-last, it never works.
msg.setSentDate(new Date());
msg.setFrom(new InternetAddress("addressFrom"));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("addressTo"));
msg.setSubject("Subject name");
msg.setText("Message here.");
Transport.send(msg);
How do I correctly send multiple attachments via Java?
This is my own email utility class, check if that the sendEmail method works for you
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
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.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class EMail {
public enum SendMethod{
HTTP, TLS, SSL
}
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
public static boolean isValidEmail(String address){
return (address!=null && address.matches(EMAIL_PATTERN));
}
public static String getLocalHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "localhost";
}
}
public static boolean sendEmail(final String recipients, final String from,
final String subject, final String contents,final String[] attachments,
final String smtpserver, final String username, final String password, final SendMethod method) {
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", smtpserver);
Session session = null;
switch (method){
case HTTP:
if (username!=null) props.setProperty("mail.user", username);
if (password!=null) props.setProperty("mail.password", password);
session = Session.getDefaultInstance(props);
break;
case TLS:
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}
});
break;
case SSL:
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.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}
});
break;
}
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(from);
message.addRecipients(Message.RecipientType.TO, recipients);
message.setSubject(subject);
Multipart multipart = new MimeMultipart();
BodyPart bodypart = new MimeBodyPart();
bodypart.setContent(contents, "text/html");
multipart.addBodyPart(bodypart);
if (attachments!=null){
for (int co=0; co<attachments.length; co++){
bodypart = new MimeBodyPart();
File file = new File(attachments[co]);
DataSource datasource = new FileDataSource(file);
bodypart.setDataHandler(new DataHandler(datasource));
bodypart.setFileName(file.getName());
multipart.addBodyPart(bodypart);
}
}
message.setContent(multipart);
Transport.send(message);
} catch(MessagingException e){
e.printStackTrace();
return false;
}
return true;
}
}
you can create a zip file from your desired folder and then send it as a normal file.
public static void main(String[] args) throws IOException {
String to = "Your desired receiver email address ";
String from = "for example your GMAIL";
//Get the session object
Properties properties = System.getProperties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
// Get the Session object.
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, "Insert your password here");
}
});
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));
message.setSubject("Write the subject");
String Final_ZIP = "C:\\Users\\Your Path\\Zipped.zip";
String FOLDER_TO_ZIP = "C:\\Users\\The folder path";
zip(FOLDER_TO_ZIP,Final_ZIP);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("Write your text");
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
DataSource source = new FileDataSource(Final_ZIP);
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("ZippedFile.zip");
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println(" Email has been sent successfully....");
} catch (MessagingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
then the Zip Function is:
public static void zip( String srcPath, String zipFilePath) throws IOException {
Path zipFileCheck = Paths.get(zipFilePath);
if(Files.exists(zipFileCheck)) { // Attention here it is deleting the old file, if it already exists
Files.delete(zipFileCheck);
System.out.println("Deleted");
}
Path zipFile = Files.createFile(Paths.get(zipFilePath));
Path sourceDirPath = Paths.get(srcPath);
try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipFile));
Stream<Path> paths = Files.walk(sourceDirPath)) {
paths
.filter(path -> !Files.isDirectory(path))
.forEach(path -> {
ZipEntry zipEntry = new ZipEntry(sourceDirPath.relativize(path).toString());
try {
zipOutputStream.putNextEntry(zipEntry);
Files.copy(path, zipOutputStream);
zipOutputStream.closeEntry();
} catch (IOException e) {
System.err.println(e);
}
});
}
System.out.println("Zip is created at : "+zipFile);
}

When I send mail Then Found Error javax.mail.AuthenticationFailedException: 535 Incorrect authentication data

I got the below error when sending an email through the below code
javax.mail.AuthenticationFailedException: 535 Incorrect authentication data
What could be the problem in my code .
public class SendMail {
public static boolean sendHTMLMail(final String from, final String password, String senderName, String sub, String msg, String[] to) {
String host = "mail.xxxx.org";
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart bodypart = new MimeBodyPart();
Properties p = new Properties();
p.setProperty("mail.smtp.host", host);
p.put("mail.smtp.port", 587);
p.put("mail.smtp.auth", "true");
try {
Session session = Session.getInstance(p, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
Transport transport = session.getTransport("smtp");
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress("" + senderName + "<" + from + ">"));
InternetAddress[] toAddress = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++) {
toAddress[i] = new InternetAddress(to[i]);
}
for (InternetAddress toAddres : toAddress) {
mimeMessage.addRecipient(Message.RecipientType.TO, toAddres);
}
bodypart.setContent(msg, "text/html; charset=\"utf-8\"");
multipart.addBodyPart(bodypart);
mimeMessage.setSubject(sub);
mimeMessage.setContent(multipart);
transport.connect(host, from, password);
mimeMessage.saveChanges();
Transport.send(mimeMessage);
transport.close();
return true;
} catch (MessagingException me) {
me.printStackTrace();
}
return false;
}
}
I have same problem in my first try ...and this code it is ok to send both in my local network and Gmail...You give a try
package SendMail;
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;
/**
* #author akash073#gmail.com
*
*/
public class CrunchifyJavaMailExample {
//static Properties mailServerProperties;
// static Session getMailSession;
// static MimeMessage generateMailMessage;
public static void main(String args[]) throws AddressException, MessagingException {
generateAndSendEmail();
System.out.println("\n\n ===> Your Java Program has just sent an Email successfully. Check your email..");
}
public static void generateAndSendEmail() throws AddressException, MessagingException {
String smtpHost="put Your Host";
String smtpUser="UserName in full #somthing.com";
String smtpPassword="your password";
int smtpPort=25;//Port may vary.Check yours smtp port
// Step1
System.out.println("\n 1st ===> setup Mail Server Properties..");
Properties mailServerProperties = System.getProperties();
//mailServerProperties.put("mail.smtp.ssl.trust", smtpHost);
// mailServerProperties.put("mail.smtp.starttls.enable", true); // added this line
mailServerProperties.put("mail.smtp.host", smtpHost);
mailServerProperties.put("mail.smtp.user", smtpUser);
mailServerProperties.put("mail.smtp.password", smtpPassword);
mailServerProperties.put("mail.smtp.port", smtpPort);
mailServerProperties.put("mail.smtp.starttls.enable", "true");
System.out.println("Mail Server Properties have been setup successfully..");
// Step2
System.out.println("\n\n 2nd ===> get Mail Session..");
Session getMailSession = Session.getDefaultInstance(mailServerProperties, null);
MimeMessage generateMailMessage = new MimeMessage(getMailSession);
generateMailMessage.setFrom (new InternetAddress (smtpUser));
generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("akash073#waltonbd.com"));
generateMailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress("akash073#gmail.com"));
generateMailMessage.setSubject("Greetings from Crunchify..");
String emailBody = "2.Test email by Crunchify.com JavaMail API example. " + "<br><br> Regards, <br>Crunchify Admin";
generateMailMessage.setContent(emailBody, "text/html");
System.out.println("Mail Session has been created successfully..");
// Step3
System.out.println("\n\n 3rd ===> Get Session and Send mail");
Transport transport = getMailSession.getTransport("smtp");
// Enter your correct gmail UserID and Password
// if you have 2FA enabled then provide App Specific Password
transport.connect(smtpHost,smtpPort, smtpUser, smtpPassword);
transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
transport.close();
}
}
just put:
p.setProperty("mail.smtps.host", host);
p.put("mail.smtps.port", 587);
p.put("mail.smtps.auth", "true");
instead of:
p.setProperty("mail.smtp.host", host);
p.put("mail.smtp.port", 587);
p.put("mail.smtp.auth", "true");

Sending an HTML e-mail with an inline image with JavaMail - Slow image loading?

When I send an HTML e-mail using JavaMail, and include an inline image in the HTML, the image takes 2-3 seconds to load when read in either Gmail or Yahoo.
The image that I am using is a small .png that is about 200 bytes in size.
Here is the code:
import java.io.File;
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.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class EmailTest
{
static String from = "Your_Gmail_Account_Name"; // (e.g., "name" if your account is "name#gmail.com"
static String password = "Your_Gmail_Password";
static String to = "Send_Here#gmail.com";
static String subject = "test";
static String body = "<h1>The image in this e-mail is slow to load.</h1><img src=\"cid:my-image\">";
static String host = "smtp.gmail.com";
public static void main(String[] args)
{
Properties properties = System.getProperties();
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.user", from);
properties.put("mail.smtp.password", password);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties);
MimeMessage message = new MimeMessage(session);
try
{
message.setFrom(new InternetAddress(from));
InternetAddress toAddress = new InternetAddress(to);
message.addRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(subject);
Multipart multipart = new MimeMultipart("related");
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(body, "text/html");
multipart.addBodyPart(htmlPart);
MimeBodyPart imagePart = new MimeBodyPart();
DataSource ds = new FileDataSource(new File("src\\icon.png"));
imagePart.setDataHandler(new DataHandler(ds));
imagePart.setHeader("Content-ID", "<my-image>");
multipart.addBodyPart(imagePart);
message.setContent(multipart);
Transport transport = session.getTransport("smtp");
try
{
transport.connect(host, from, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("e-mail sent.");
}
catch (MessagingException e)
{
e.printStackTrace();
}
}
catch (AddressException e)
{
e.printStackTrace();
}
catch (MessagingException e)
{
e.printStackTrace();
}
}
}
Does anyone know why the image is so slow to load?
UPDATE:
When reading the e-mail produced by the above code in Thunderbird, the image wouldn't even load, but would only show up as an attachment.
But if I remove this line:
imagePart.setHeader("Content-ID", "<my-image>");
and replace it with these two lines:
imagePart.addHeader("Content-ID", "<my-image>");
imagePart.addHeader("Content-Type", "image/png");
then the image actually loads in Thunderbird, and loads instantaneously.
However, the image is still slow to load in both Gmail and Yahoo.
Perhaps they're running a virus scanner on it? Try Thunderbird.
As Bill and the other poster mentioned, the problem is not an issue with JavaMail, but appears to be an issue with Gmail and Yahoo scanning embedded inline images sent in e-mails.
The solution is to not embed any inline images in your HTML e-mail with a Content-ID, but to place a src attribute in your img tags in your HTML that refers to your images that are sitting on a remote host.
This will make your images load very quickly when they are sent inside an HTML e-mail.
In other words:
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 EmailTest
{
static String from = "Your_Gmail_Account_Name"; // Your Gmail account name (e.g., "name" if your account is "name#gmail.com"
static String password = "Your_Gmail_Password"; // Your Gmail password
static String to = "Send_Here#gmail.com";
static String subject = "test";
static String body = "<html><body><h1>The image in this e-mail loads very fast.</h1><img src=\"http://www.your_host.com/path/to/image/icon.png\"></body></html>";
static String host = "smtp.gmail.com";
public static void main(String[] args)
{
Properties properties = System.getProperties();
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.user", from);
properties.put("mail.smtp.password", password);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties);
MimeMessage message = new MimeMessage(session);
try
{
message.setFrom(new InternetAddress(from));
InternetAddress toAddress = new InternetAddress(to);
message.addRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(subject);
message.setContent(body, "text/html");
Transport transport = session.getTransport("smtp");
try
{
transport.connect(host, from, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("e-mail sent.");
}
catch (MessagingException e)
{
e.printStackTrace();
}
}
catch (AddressException e)
{
e.printStackTrace();
}
catch (MessagingException e)
{
e.printStackTrace();
}
}
}

java mail API exception

I got this exception when trying to send mail from web application:
com.sun.mail.smtp.SMTPSendFailedException: 550 5.7.1 Missing
or literal domains not allowed
I am using properties like below code.
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.verizon.net");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
I also authenticate the users using username and password using authenticate method.
I got success message only when i'm authenticate. I got exception when i go to line called transport.sen(message).
this is my full code..
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
to));
// message.addRecipient(Message.RecipientType.CC, new InternetAddress(
// cc));
// message.addRecipient(Message.RecipientType.BCC,
// new InternetAddress(bcc));
message.setSubject("TEST...!!!!!!!");
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart
.setText("Dear Sir, Mail Testing");
multipart.addBodyPart(messageBodyPart);
messageBodyPart.setText("Hao test");
message.setText("Kader here");
message.setContent(multipart);
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
Transport transport = session.getTransport();
transport.connect();
Transport.send(message);
transport.close();
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
There is possibility that Some mail servers automatically append the domain name to the user name when client logging but some server will not, hence fail the authentication.
Try this code :-
MailUtil.java
------------
package com.test;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
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.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* Please test with your GMAIL
* #author Jamsheer T
* +91-9846716175
*
*/
public class MailUtil {
private String SMTP_HOST = "smtp.gmail.com";
private String FROM_ADDRESS = "jamsheer568#gmail.com"; //Give Your gmail here
private String PASSWORD = "***********"; //Give Your password here
private String FROM_NAME = "Jamsheer T";
public boolean sendMail(String[] recipients, String[] bccRecipients, String subject,
String message) {
try {
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "false");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.starttls.enable","true");
Session session = Session.getInstance(props, new SocialAuth());
Message msg = new MimeMessage(session);
InternetAddress from = new InternetAddress(FROM_ADDRESS, FROM_NAME);
msg.setFrom(from);
InternetAddress[] toAddresses = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
toAddresses[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, toAddresses);
InternetAddress[] bccAddresses = new InternetAddress[bccRecipients.length];
for (int j = 0; j < bccRecipients.length; j++) {
bccAddresses[j] = new InternetAddress(bccRecipients[j]);
}
msg.setRecipients(Message.RecipientType.BCC, bccAddresses);
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
return true;
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null, ex);
return false;
} catch (MessagingException ex) {
ex.printStackTrace();
Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
}
class SocialAuth extends Authenticator {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(FROM_ADDRESS, PASSWORD);
}
}
}
Main.java
----------------
package com.test;
public class Main {
public static void main(String[] args) {
String[] recipients = new String[]{"example1#gmail.com"}; //To
String[] bccRecipients = new String[]{"example2#gmail.com"}; //Bcc
String subject = "Test Mail"; //Subject
String messageBody = "Hi how r u?????"; //Body
System.out.print("Result"+new MailUtil().sendMail(recipients, bccRecipients,
subject, messageBody));
}
}

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

Is it possible to send an email from my Java application using a GMail account? I have configured my company mail server with Java app to send email, but that's not going to cut it when I distribute the application. Answers with any of using Hotmail, Yahoo or GMail are acceptable.
First download the JavaMail API and make sure the relevant jar files are in your classpath.
Here's a full working example using GMail.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Main {
private static String USER_NAME = "*****"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "********"; // GMail password
private static String RECIPIENT = "lizard.bill#myschool.edu";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "Welcome to JavaMail!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
Naturally, you'll want to do more in the catch blocks than print the stack trace as I did in the example code above. (Remove the catch blocks to see which method calls from the JavaMail API throw exceptions so you can better see how to properly handle them.)
Thanks to #jodonnel and everyone else who answered. I'm giving him a bounty because his answer led me about 95% of the way to a complete answer.
Something like this (sounds like you just need to change your SMTP server):
String host = "smtp.gmail.com";
String from = "user name";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "asdfgh");
props.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mail
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress[] to_address = new InternetAddress[to.length];
int i = 0;
// To get the array of addresses
while (to[i] != null) {
to_address[i] = new InternetAddress(to[i]);
i++;
}
System.out.println(Message.RecipientType.TO);
i = 0;
while (to_address[i] != null) {
message.addRecipient(Message.RecipientType.TO, to_address[i]);
i++;
}
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
// alternately, to send HTML mail:
// message.setContent("<p>Welcome to JavaMail</p>", "text/html");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.mail.yahoo.co.in", "user name", "asdfgh");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
Other people have good answers above, but I wanted to add a note on my experience here. I've found that when using Gmail as an outbound SMTP server for my webapp, Gmail only lets me send ~10 or so messages before responding with an anti-spam response that I have to manually step through to re-enable SMTP access. The emails I was sending were not spam, but were website "welcome" emails when users registered with my system. So, YMMV, and I wouldn't rely on Gmail for a production webapp. If you're sending email on a user's behalf, like an installed desktop app (where the user enters their own Gmail credentials), you may be okay.
Also, if you're using Spring, here's a working config to use Gmail for outbound SMTP:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="defaultEncoding" value="UTF-8"/>
<property name="host" value="smtp.gmail.com"/>
<property name="port" value="465"/>
<property name="username" value="${mail.username}"/>
<property name="password" value="${mail.password}"/>
<property name="javaMailProperties">
<value>
mail.debug=true
mail.smtp.auth=true
mail.smtp.socketFactory.class=java.net.SocketFactory
mail.smtp.socketFactory.fallback=false
</value>
</property>
</bean>
Even though this question is closed, I'd like to post a counter solution, but now using Simple Java Mail (Open Source JavaMail smtp wrapper):
final Email email = new Email();
String host = "smtp.gmail.com";
Integer port = 587;
String from = "username";
String pass = "password";
String[] to = {"to#gmail.com"};
email.setFromAddress("", from);
email.setSubject("sending in a group");
for( int i=0; i < to.length; i++ ) {
email.addRecipient("", to[i], RecipientType.TO);
}
email.setText("Welcome to JavaMail");
new Mailer(host, port, from, pass).sendMail(email);
// you could also still use your mail session instead
new Mailer(session).sendMail(email);
My complete code as below is working well:
package ripon.java.mail;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail
{
public static void main(String [] args)
{
// Sender's email ID needs to be mentioned
String from = "test#gmail.com";
String pass ="test123";
// Recipient's email ID needs to be mentioned.
String to = "ripon420#yahoo.com";
String host = "smtp.gmail.com";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.user", from);
properties.put("mail.smtp.password", pass);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
// 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 transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
//set CLASSPATH=%CLASSPATH%;activation.jar;mail.jar
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class Mail
{
String d_email = "iamdvr#gmail.com",
d_password = "****",
d_host = "smtp.gmail.com",
d_port = "465",
m_to = "iamdvr#yahoo.com",
m_subject = "Testing",
m_text = "Hey, this is the testing email using smtp.gmail.com.";
public static void main(String[] args)
{
String[] to={"XXX#yahoo.com"};
String[] cc={"XXX#yahoo.com"};
String[] bcc={"XXX#yahoo.com"};
//This is for google
Mail.sendMail("venkatesh#dfdf.com", "password", "smtp.gmail.com",
"465", "true", "true",
true, "javax.net.ssl.SSLSocketFactory", "false",
to, cc, bcc,
"hi baba don't send virus mails..",
"This is my style...of reply..If u send virus mails..");
}
public synchronized static boolean sendMail(
String userName, String passWord, String host,
String port, String starttls, String auth,
boolean debug, String socketFactoryClass, String fallback,
String[] to, String[] cc, String[] bcc,
String subject, String text)
{
Properties props = new Properties();
//Properties props=System.getProperties();
props.put("mail.smtp.user", userName);
props.put("mail.smtp.host", host);
if(!"".equals(port))
props.put("mail.smtp.port", port);
if(!"".equals(starttls))
props.put("mail.smtp.starttls.enable",starttls);
props.put("mail.smtp.auth", auth);
if(debug) {
props.put("mail.smtp.debug", "true");
} else {
props.put("mail.smtp.debug", "false");
}
if(!"".equals(port))
props.put("mail.smtp.socketFactory.port", port);
if(!"".equals(socketFactoryClass))
props.put("mail.smtp.socketFactory.class",socketFactoryClass);
if(!"".equals(fallback))
props.put("mail.smtp.socketFactory.fallback", fallback);
try
{
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
msg.setText(text);
msg.setSubject(subject);
msg.setFrom(new InternetAddress("p_sambasivarao#sutyam.com"));
for(int i=0;i<to.length;i++) {
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(to[i]));
}
for(int i=0;i<cc.length;i++) {
msg.addRecipient(Message.RecipientType.CC,
new InternetAddress(cc[i]));
}
for(int i=0;i<bcc.length;i++) {
msg.addRecipient(Message.RecipientType.BCC,
new InternetAddress(bcc[i]));
}
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, userName, passWord);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return true;
}
catch (Exception mex)
{
mex.printStackTrace();
return false;
}
}
}
The minimum required:
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.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MessageSender {
public static void sendHardCoded() throws AddressException, MessagingException {
String to = "a#a.info";
final String from = "b#gmail.com";
Properties properties = new Properties();
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, "BeNice");
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Hello");
message.setText("What's up?");
Transport.send(message);
}
}
The posted code solutions may cause problems when you need to set up multiple SMTP sessions anywhere within the same JVM.
The JavaMail FAQ recommends using
Session.getInstance(properties);
instead of
Session.getDefaultInstance(properties);
because the getDefault will only use the properties given the first time it is invoked. All later uses of the default instance will ignore property changes.
See http://www.oracle.com/technetwork/java/faq-135477.html#getdefaultinstance
Value added:
encoding pitfalls in subject, message and display name
only one magic property is needed for modern java mail library versions
Session.getInstance() recommended over Session.getDefaultInstance()
attachment in the same example
still works after Google turns off less secure apps: Enable 2-factor authentication in your organization -> turn on 2FA -> generate app password.
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.DataHandler;
import javax.mail.Message;
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.mail.util.ByteArrayDataSource;
public class Gmailer {
private static final Logger LOGGER = Logger.getLogger(Gmailer.class.getName());
public static void main(String[] args) {
send();
}
public static void send() {
Transport transport = null;
try {
String accountEmail = "account#source.com";
String accountAppPassword = "";
String displayName = "Display-Name 東";
String replyTo = "reply-to#source.com";
String to = "to#target.com";
String cc = "cc#target.com";
String bcc = "bcc#target.com";
String subject = "Subject 東";
String message = "<span style='color: red;'>東</span>";
String type = "html"; // or "plain"
String mimeTypeWithEncoding = "text/" + type + "; charset=" + StandardCharsets.UTF_8.name();
File attachmentFile = new File("Attachment.pdf");
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
String attachmentMimeType = "application/pdf";
byte[] bytes = ...; // read file to byte array
Properties properties = System.getProperties();
properties.put("mail.debug", "true");
// i found that this is the only property necessary for a modern java mail version
properties.put("mail.smtp.starttls.enable", "true");
// https://javaee.github.io/javamail/FAQ#getdefaultinstance
Session session = Session.getInstance(properties);
MimeMessage mimeMessage = new MimeMessage(session);
// probably best to use the account email address, to avoid landing in spam or blacklists
// not even sure if the server would accept a differing from address
InternetAddress from = new InternetAddress(accountEmail);
from.setPersonal(displayName, StandardCharsets.UTF_8.name());
mimeMessage.setFrom(from);
mimeMessage.setReplyTo(InternetAddress.parse(replyTo));
mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
mimeMessage.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
mimeMessage.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
mimeMessage.setSubject(subject, StandardCharsets.UTF_8.name());
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setContent(mimeMessage, mimeTypeWithEncoding);
multipart.addBodyPart(messagePart);
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.setDataHandler(new DataHandler(new ByteArrayDataSource(bytes, attachmentMimeType)));
attachmentPart.setFileName(attachmentFile.getName());
multipart.addBodyPart(attachmentPart);
mimeMessage.setContent(multipart);
transport = session.getTransport();
transport.connect("smtp.gmail.com", 587, accountEmail, accountAppPassword);
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
}
catch(Exception e) {
// I prefer to bubble up exceptions, so the caller has the info that someting went wrong, and gets a chance to handle it.
// I also prefer not to force the exception in the signature.
throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
}
finally {
if(transport != null) {
try {
transport.close();
}
catch(Exception e) {
LOGGER.log(Level.WARNING, "failed to close java mail transport: " + e);
}
}
}
}
}
This is what I do when i want to send email with attachment, work fine. :)
public class NewClass {
public static void main(String[] args) {
try {
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465"); // smtp port
Authenticator auth = new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username-gmail", "password-gmail");
}
};
Session session = Session.getDefaultInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("username-gmail#gmail.com"));
msg.setSubject("Try attachment gmail");
msg.setRecipient(RecipientType.TO, new InternetAddress("username-gmail#gmail.com"));
//add atleast simple body
MimeBodyPart body = new MimeBodyPart();
body.setText("Try attachment");
//do attachment
MimeBodyPart attachMent = new MimeBodyPart();
FileDataSource dataSource = new FileDataSource(new File("file-sent.txt"));
attachMent.setDataHandler(new DataHandler(dataSource));
attachMent.setFileName("file-sent.txt");
attachMent.setDisposition(MimeBodyPart.ATTACHMENT);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
multipart.addBodyPart(attachMent);
msg.setContent(multipart);
Transport.send(msg);
} catch (AddressException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
} catch (MessagingException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
An easy route would be to have the gmail account configured/enabled for POP3 access. This would allow you to send out via normal SMTP through the gmail servers.
Then you'd just send through smtp.gmail.com (on port 587)
Hi try this code....
package my.test.service;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Sample {
public static void main(String args[]) {
final String SMTP_HOST = "smtp.gmail.com";
final String SMTP_PORT = "587";
final String GMAIL_USERNAME = "xxxxxxxxxx#gmail.com";
final String GMAIL_PASSWORD = "xxxxxxxxxx";
System.out.println("Process Started");
Properties prop = System.getProperties();
prop.setProperty("mail.smtp.starttls.enable", "true");
prop.setProperty("mail.smtp.host", SMTP_HOST);
prop.setProperty("mail.smtp.user", GMAIL_USERNAME);
prop.setProperty("mail.smtp.password", GMAIL_PASSWORD);
prop.setProperty("mail.smtp.port", SMTP_PORT);
prop.setProperty("mail.smtp.auth", "true");
System.out.println("Props : " + prop);
Session session = Session.getInstance(prop, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(GMAIL_USERNAME,
GMAIL_PASSWORD);
}
});
System.out.println("Got Session : " + session);
MimeMessage message = new MimeMessage(session);
try {
System.out.println("before sending");
message.setFrom(new InternetAddress(GMAIL_USERNAME));
message.addRecipients(Message.RecipientType.TO,
InternetAddress.parse(GMAIL_USERNAME));
message.setSubject("My First Email Attempt from Java");
message.setText("Hi, This mail came from Java Application.");
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(GMAIL_USERNAME));
Transport transport = session.getTransport("smtp");
System.out.println("Got Transport" + transport);
transport.connect(SMTP_HOST, GMAIL_USERNAME, GMAIL_PASSWORD);
transport.sendMessage(message, message.getAllRecipients());
System.out.println("message Object : " + message);
System.out.println("Email Sent Successfully");
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here's an easy-to-use class for sending emails with Gmail. You need to have the JavaMail library added to your build path or just use Maven.
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.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 GmailSender
{
private static String protocol = "smtp";
private String username;
private String password;
private Session session;
private Message message;
private Multipart multipart;
public GmailSender()
{
this.multipart = new MimeMultipart();
}
public void setSender(String username, String password)
{
this.username = username;
this.password = password;
this.session = getSession();
this.message = new MimeMessage(session);
}
public void addRecipient(String recipient) throws AddressException, MessagingException
{
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
}
public void setSubject(String subject) throws MessagingException
{
message.setSubject(subject);
}
public void setBody(String body) throws MessagingException
{
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(body);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
}
public void send() throws MessagingException
{
Transport transport = session.getTransport(protocol);
transport.connect(username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
public void addAttachment(String filePath) throws MessagingException
{
BodyPart messageBodyPart = getFileBodyPart(filePath);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
}
private BodyPart getFileBodyPart(String filePath) throws MessagingException
{
BodyPart messageBodyPart = new MimeBodyPart();
DataSource dataSource = new FileDataSource(filePath);
messageBodyPart.setDataHandler(new DataHandler(dataSource));
messageBodyPart.setFileName(filePath);
return messageBodyPart;
}
private Session getSession()
{
Properties properties = getMailServerProperties();
Session session = Session.getDefaultInstance(properties);
return session;
}
private Properties getMailServerProperties()
{
Properties properties = System.getProperties();
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", protocol + ".gmail.com");
properties.put("mail.smtp.user", username);
properties.put("mail.smtp.password", password);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
return properties;
}
}
Example usage:
GmailSender sender = new GmailSender();
sender.setSender("myEmailNameWithout#gmail.com", "mypassword");
sender.addRecipient("recipient#somehost.com");
sender.setSubject("The subject");
sender.setBody("The body");
sender.addAttachment("TestFile.txt");
sender.send();
If you want to use outlook with Javamail API then use
smtp-mail.outlook.com
as a host for more and complete working code Check out this answer.

Categories