I am trying to send emails with attachments in background.
I am not able to do it with/without attachments.
Not sure where am I going wrong.
Can someone please help me in resolving the issue ?
Thanks.
Error Log:
javax.mail.NoSuchProviderException: Invalid protocol: null
javax.mail.Session.getProvider(Session.java:441)
javax.mail.Session.getTransport(Session.java:660)
javax.mail.Session.getTransport(Session.java:641)
javax.mail.Session.getTransport(Session.java:627)
com.test.www.test.MailClass.doInBackground(MailClass.java:43)
com.test.www.test.DelAddress$1.run(DelAddress.java:82)
java.lang.Thread.run(Thread.java:818)
Code Snippet:
class MailClass extends AsyncTask<String, Void, Void> {
MimeMessage email;
String delAddress, pathsList, user, password;
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart attachPart = new MimeBodyPart();
DataSource source;
Session session;
protected Void doInBackground( ArrayList<String> imagePaths, String address) throws MessagingException, UnsupportedEncodingException, EmailException {
setupEmailConfig();
deliveryAddress = address;
Log.i("doInBackground, Count:", String.valueOf(imagePaths.size()));
createEmail(imagePaths);
Log.i("doInBackground:", "Email Created Successfully.");
try {
Transport transport = session.getTransport();
transport.connect();
transport.sendMessage(email, email.getRecipients(Message.RecipientType.TO));
transport.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
Log.i("doInBackground:", "Email Sent.");
return null;
}
private void setupEmailConfig() {
user = "abc#gmail.com";
password = "abc";
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.googlemail.com");
properties.put("mail.smtp.port", "465");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", user);
properties.put("mail.password", password);
session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
}
private void createEmail(ArrayList<String> imagePaths) throws EmailException,
MessagingException, IOException {
String recip = "xyz#gmail.com";
email = new MimeMessage(session);
email.setFrom(new InternetAddress(user));
email.addRecipient(Message.RecipientType.TO, new InternetAddress(recip));
email.setSubject("Test Mail");
email.setSentDate(new Date());
pathsList = "";
for(int i=0; i<imagePaths.size(); i++) {
pathsList += "\r\n" + String.valueOf(i+1) + ") " + imagePaths.get(i);
// attachPart.attachFile(imagePaths.get(i));
// source = new FileDataSource(imagePaths.get(i));
// attachPart.setDataHandler(new DataHandler(source));
// attachPart.setFileName(new File(imagePaths.get(i)).getName());
// multipart.addBodyPart(attachPart);
}
BodyPart messageBody = new MimeBodyPart();
messageBody.setText("Text Body");
multipart.addBodyPart(messageBody);
email.setContent(multipart);
}
#Override
protected Void doInBackground(String... params) {
return null;
}
}
Made Few Changes. Working Code.
Code:
class MailClass extends AsyncTask<String, Void, Void> {
MimeMessage email;
String delAddress, pathsList, user, password;
MimeMultipart multipart = new MimeMultipart();
Session session;
protected Void doInBackground( ArrayList<String> imagePaths, String address) throws MessagingException, IOException, EmailException {
setupEmailConfig();
delAddress = address;
Log.i("doInBackground, Count:", String.valueOf(imagePaths.size()));
createEmail(imagePaths);
Log.i("doInBackground:", "Email Created Successfully.");
Transport.send(email);
Log.i("doInBackground:", "Email Sent.");
return null;
}
private void setupEmailConfig() {
user = "abc#gmail.com";
password = "abc";
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.user", user);
properties.put("mail.password", password);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "465");
properties.put("mail.smtp.starttls.enable", "true");
session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
}
private void createEmail(ArrayList<String> imagePaths) throws EmailException, MessagingException, IOException {
String receiver = "abc#gmail.com";
String receiverCC = "abc#gmail.com";
email = new MimeMessage(session);
email.setFrom(new InternetAddress(user, user));
email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(receiver, receiver));
email.addRecipient(Message.RecipientType.CC, new InternetAddress(receiverCC));
email.setSubject("Customer Order");
email.setSentDate(new Date());
pathsList = "";
for(int i=0; i<imagePaths.size(); i++) {
pathsList += "\r\n" + String.valueOf(i+1) + ") " + imagePaths.get(i);
MimeBodyPart attachPart = new MimeBodyPart();
attachPart.setDataHandler(new DataHandler(new FileDataSource(imagePaths.get(i))));
attachPart.setFileName(new File(imagePaths.get(i)).getName());
multipart.addBodyPart(attachPart);
}
MimeBodyPart messageBody = new MimeBodyPart();
messageBody.setText("Body Text." +
delAddress + "\r\n List of Images: " + pathsList);
multipart.addBodyPart(messageBody);
email.setContent(multipart);
}
#Override
protected Void doInBackground(String... params) {
return null;
}
}
Related
In Javamail Attachment is not displaying
I tried to send a mail with attachment
It sending and received But in received mail attachment is not displaying not display
attachment is blank and
Here the code is:
#Bean
public JavaMailSenderImpl mailSender() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setProtocol("smtp");
javaMailSender.setHost("smtp.gmail.com");
javaMailSender.setPort(587);
javaMailSender.setUsername("*******#gmail.com");
javaMailSender.setPassword("*********");
Properties props = ((JavaMailSenderImpl) javaMailSender).getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
props.put("mail.mime.multipart.allowempty", "true");
javaMailSender.setJavaMailProperties(props);
return javaMailSender;
}
{
message.setSubject(mailServiceDTO.getSubject());
message.setText(mailServiceDTO.getSubject(), "text/html");
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(mailServiceDTO.getSubject(), "text/html");
for (EmailAttachment attachment : mailServiceDTO.getAttachments()) {
message.addAttachment(attachment.getAttachmentName(), new ByteArrayResource(attachment.getAttachmentContent().getBytes()));
}
Multipart mp = new MimeMultipart();
mp.addBodyPart(messageBodyPart);
mimeMessage.setContent(mp);
javaMailSender.send(mimeMessage);
}
you can use MimeMessageHelper in spring mail.
Example
MimeMessage msg = javaMailSender.createMimeMessage();
MimeMessageHelper mailMessage = null;
List<PathSource> pathSourceList = request.getMailAttachList();
if (pathSourceList != null && pathSourceList.size() > 0)
mailMessage = new MimeMessageHelper(msg, true);
else
mailMessage = new MimeMessageHelper(msg, false);
// ....
if (pathSourceList != null && pathSourceList.size() > 0) {
for (PathSource filepath : pathSourceList) {
ByteArrayResource stream = new ByteArrayResource(DatatypeConverter.parseBase64Binary(
filepath.getData()));
mailMessage.addAttachment(filepath.getFileName(), stream);
}
}
try {
javaMailSender.send(mailMessage.getMimeMessage());
} catch (Exception ex) {
log.error("server info {}", serverModel.toString());
throw ex;
}
Add Multiple attachments..
public static void main(String[] args) {
final String fromEmail = ""; // requires valid gmail id
final String password = "";// correct password for gmail id
final String toEmail = ""; // can be any
System.out.println("TLSEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); // SMTP Host
props.put("mail.smtp.port", "587"); // TLS Port
props.put("mail.smtp.auth", "true"); // enable authentication
props.put("mail.smtp.starttls.enable", "true"); // enable STARTTLS
Authenticator auth = new Authenticator() {
// override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getDefaultInstance(props, auth);
System.out.println("Session created");
sendAttachmentEmail(session,fromEmail, toEmail,"SSLEmail Testing Subject with Attachment", "SSLEmail Testing Body with Attachment");
}
public static void sendAttachmentEmail(Session session,String fromEmail, String toEmail, String subject, String body){
try{
MimeMessage msg = new MimeMessage(session);
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress(fromEmail));
msg.setReplyTo(InternetAddress.parse(toEmail, false));
msg.setSubject(subject, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
// Create the message body part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(body);
// Create a multipart message for attachment
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
String filename1 = "C:\\TraingWorkspace\\Training\\logs\\DailyLog.zip";
addAttachment(multipart, filename1);
String filename2 = "C:\\TraingWorkspace\\Training\\logs\\DailyLog.log";
addAttachment(multipart, filename2);
// Send the complete message parts
msg.setContent(multipart);
// Send message
Transport.send(msg);
System.out.println("EMail Sent Successfully with attachment!!");
}catch (MessagingException e) {
e.printStackTrace();
}
}
private static void addAttachment(Multipart multipart, String filename) throws MessagingException
{
DataSource source = new FileDataSource(filename);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
}
I have an web application in which i am sending mail to user. Following is my code.
String host = "smtp.gmail.com";
String pwd = "123";
String from = "sender#gmail.com";
String to = "receiver#gmail.com";
String subject = "Test";
String messageText = "This is demo mail";
int port = 587;
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.required", "true");
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] add = {new InternetAddress(to)};
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setRecipients(Message.RecipientType.TO, add);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText); //Actual msg
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, from, pwd);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
This code is executed on local but fails on server domain. I have search a lot but that solution didn't work for me.
I tried a lot like replacing transport.connect(host, from, pwd); with transport.connect(host, 587, from, pwd); or 465and also String host="smtp.gmail.com"; with static domain IP. but still not working.
can anyone figure out what i am missing..?
Here is working example.
If this didn't work then there must be a problem with your server..
public static void sendEmail(String host, String port, final String userName, final String password, String recipient, String subject, String message, File attachFile) throws AddressException, MessagingException, UnsupportedEncodingException {
// sets SMTP server properties
try {
logger.info("Sending Email to : " + recipient + " Subject :" + subject);
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() {
#Override
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, userName));
if (recipient.contains(";")) {
String[] recipientList = recipient.split(";");
InternetAddress[] recipientAddress = new InternetAddress[recipientList.length];
int counter = 0;
for (String obj: recipientList) {
recipientAddress[counter] = new InternetAddress(obj.trim());
counter++;
}
msg.setRecipients(Message.RecipientType.TO, recipientAddress);
} else {
InternetAddress[] recipientAddress = {
new InternetAddress(recipient)
};
msg.setRecipients(Message.RecipientType.TO, recipientAddress);
}
msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (attachFile != null) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(attachFile);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
} catch (Exception e) {
logger.error("ERROR In Sending Email :" + e, e);
}
}
I want to read HTML file and want to send HTML formatted email.
public class SendEmailer {
public void sendHtmlEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) throws AddressException,
MessagingException {
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// sets SMTP server properties
Properties properties = new Properties();
properties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
properties.setProperty("mail.smtp.socketFactory.fallback", "false");
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.store.protocol","pop3");
properties.put("mail.transport.protocol","smtp");
// 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());
// set plain text message
msg.setContent(message, "text/html");
// sends the e-mail
Transport.send(msg);
}
//Code to read HTML document.
public void readHTML(String strfilename,String content){
// content="";
String str="";
try{
FileReader fr=new FileReader(strfilename);
BufferedReader br=new BufferedReader(fr);
while((str=br.readLine())!=null){
System.out.println(str.toString());
content+=str;
}
br.close();
}catch(IOException ie){
ie.printStackTrace();
}
}
public static void main(String[] args) {
// SMTP server information
String host = "myhost.com";
String port = "465";
String mailFrom = "abc#myhost.com";
String password = "abcd123";
// outgoing message information
String mailTo = "abc#gmail.com";
String subject = "Test mail";
// message contains HTML markups
String message = "<i>Greetings!Sending HTML mail.</i><br>";
message += "<font color=red>MyName</font>";
SendEmailer mailer = new SendEmailer ();
String filename="E:/filepath/filename.html";
try {
mailer.readHTML(filename);
mailer.sendHtmlEmail(host, port, mailFrom, password, mailTo,
subject, message);
System.out.println("Email sent successfully.");
} catch (Exception ex) {
System.out.println("Failed to sent email.");
ex.printStackTrace();
}
}
}
I am able to send email successfully. But now I want to send the full body part of the html file. I wrote a method readHTML(), but its not reading the content of that file neither it sends the same. It sends only what I've stored in message variable. Where did I make mistake?
i have the following code to send an email with attachment. The problem is, that the attachment, which is a simple text file, is empty. But the file isn't.
Just in the email it is. The text is showing correctly. No error codes.
private void emailSenden() throws MessagingException, FileNotFoundException, IOException {
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "587");
Authenticator auth = new SMTPAuthenticator();
Session mailSession = Session.getDefaultInstance(props, auth);
MimeMessage msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress("xyz#xxx.de", "Muster AG"));
msg.setRecipients(Message.RecipientType.TO, "abc#aaa.de");
msg.setSubject("Update erfolgreich.");
msg.setSentDate(new Date());
try {
Multipart mp = new MimeMultipart();
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("Update erfolgreich");
mp.addBodyPart(textPart);
MimeBodyPart attachFilePart = new MimeBodyPart();
attachFilePart.attachFile(new File("C:" + File.separator + "log" + File.separator + "logDatei.txt"));
mp.addBodyPart(attachFilePart);
msg.setContent(mp);
msg.saveChanges();
Transport.send(msg);
System.out.println("Email gesendet");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}
try this
attachFilePart = new MimeBodyPart();
String filename = "c:\log\logDatei.txt";
DataSource source = new FileDataSource(filename);
attachFilePart .setDataHandler(new DataHandler(source));
attachFilePart .setFileName(filename);
multipart.addBodyPart(attachFilePart );
I try to send emails using jsp. All the things working perfect but when I try to use more than one email addresses it shows error ,
javax.mail.internet.AddressException: Illegal address in string ``
here is my code
public EmailSender(String[] to, String subject, String msg) {
final String txtFromAcc = "abeywicrema#gmail.com";
final String pwfFromPW = "mjkkmqzrkkgsydqk";
String txtFrom = "norply#politeknick.com";
//String txtTo = "abeywicrema#gmail.comshan.a#jinasena.com.lk";//to;
String txtSubject = subject;
String txaMessage = msg;
String[] sendMore = to;//{"abeywicrema#gmail.com", "shan.a#jinasena.com.lk"};
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties prop = new Properties();
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.port", "465");
prop.put("mail.smtp.socketFactory.port", "465");
prop.put("mail.debug", "true");
prop.put("mail.smtp.socketFactory.port", "465");
prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
prop.put("mail.smtp.socketFactory.fallback", "false");
Authenticator auth = new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(txtFromAcc, pwfFromPW);
}
};
Session session = Session.getDefaultInstance(prop, auth);
try {
Message mail = new MimeMessage(session);
mail.setFrom(new InternetAddress(txtFrom));
InternetAddress[] addressTo = new InternetAddress[sendMore.length];
for (int i = 0; i < sendMore.length; i++) {
addressTo[i] = new InternetAddress(sendMore[i]);
}
mail.setRecipients(Message.RecipientType.TO, addressTo);
mail.setSubject(txtSubject);
mail.setContent(txaMessage, "text/plain");
Transport.send(mail);
//OptionPane.showMessageDialog(this, "Sent");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(">>>>>>>>>>>>>>>>msg has been sent ");
}