I am trying to send email in background. Everything is working fine i am getting mail also but the problem is i am not getting email body and attachment in email.
I am not getting any error or any exception, i am getting mail also in my mail id but just the problem is attachment and email body, in attachment i am trying to send image from sdcard. So what is the problem in the following code. Can anyone help.
GMailSender.java
public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
private Multipart _multipart;
static {
Security.addProvider(new JSSEProvider());
}
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
_multipart = new MimeMultipart();
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body,
String sender, String recipients) throws Exception {
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(
body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
message.setContent(_multipart);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(
recipients));
Transport.send(message);
}
public void addAttachment(String filename) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}
JSSEProvider.java
public class JSSEProvider extends Provider {
private static final long serialVersionUID = 1L;
public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController
.doPrivileged(new java.security.PrivilegedAction<Void>() {
public Void run() {
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
});
}
}
Activity.java
Button mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
new sendEmail().execute();
}
});
and
public class sendEmail extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
try {
String subject = "Registration";
String message = "Thank you for regestering with";
String senderOfmail = "abcd#gmail.com";
String receiver = "abcd#gmail.com";
GMailSender sender = new GMailSender(
"abcd#gmail.com", "abcde12345");
sender.sendMail(subject, message, senderOfmail, receiver);
FileOutputStream outStream;
File file;
Bitmap bm = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
String extStorageDirectory = Environment
.getExternalStorageDirectory().toString();
file = new File(extStorageDirectory, "ic_launcher.PNG");
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
String fileName = file.toString().trim();
sender.addAttachment(fileName);
} catch (Exception e) {
Toast.makeText(Signup.this,
"There was a problem sending the email.",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e("error", e.getMessage(), e);
return "Email Not Sent";
}
return "Email Sent";
}
}
Related
I created a program that sends files to email in Java. How to insert a timer that will automatically send mail every 2 minutes?
I think it could be through a timer, but if someone has a different way or encountered this or a similar problem, it would help me a lot.
Here's the code:
public class EMail {
public static void main(String[] args)
{
SendEmail();
}
private static void SendEmail ()
{
final String username = "youremail#gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("youremail#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("youremail#gmail.com"));
message.setSubject("Testing Subject");
message.setText("PFA");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String file = "C:\\Users\\Name\\UserData\\Logs.txt";
String fileName = "Logs.txt";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
System.out.println("Sending");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
You can do something like this.This code will enable you to send mails for every two minutes.
public class EmailHandler{
public static void main(String[] args){
Thread emailSenderThread = new Thread(new EmailSender());
emailSenderThread.start();
}
private static class EmailSender implements Runnable {
private void sendEmail(){
//Email sending logic Impl
}
#Override
public void run() {
for(;;){
sendEmail();
try {
Thread.sleep(120000);//Thread is sleeping for 2 minutes
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
}
You can use Timer and TimerTask which are java util classes used to schedule tasks in a background thread
Example (You can add this to main method):
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
SendEmail();
}
};
Timer timer = new Timer("MyTimer");
timer.scheduleAtFixedRate(timerTask, 500, 2000);
I integrated in my JavaMail application, allowing me to send an email via Java (I use Gmail) it works without problems but when I use it on another connection, it no longer works.
He shows me this error :
enter image description here
There is my Mail code :
public class SupportMail {
private static String LOGIN_SMTP1="login";
private static String PASSWORD_SMTP1="pwd";
private static String SMTP_HOST1="smtp.gmail.com";
private static String IMAP_ACCOUNT1="rollandgame#gmail.com";
private static String receiver = "floriangenicq#gmail.com";
private static String copyRecei = "floriangenicq#gmail.com";
public SupportMail() {
}
public static void sendMessage(String subject, String text) {
// Création de la session
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", "smtp");
properties.put("mail.smtp.ssl.trust", SMTP_HOST1);
properties.setProperty("mail.smtp.host", SMTP_HOST1);
properties.setProperty("mail.smtp.user", LOGIN_SMTP1);
properties.setProperty("mail.from", IMAP_ACCOUNT1);
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.port", 587);
properties.put("mail.smtp.auth", "true");
Session session = Session.getInstance(properties);
// Création du message
MimeMessage message = new MimeMessage(session);
try {
message.setText(text);
message.setSubject(subject);
} catch (MessagingException e) {
e.printStackTrace();
}
// Envoie du mail
Transport transport = null;
try {
transport = session.getTransport("smtp");
transport.connect(LOGIN_SMTP1, PASSWORD_SMTP1);
transport.sendMessage(message, new Address[] { new InternetAddress(receiver),
new InternetAddress(copyRecei) });
} catch (MessagingException e) {
e.printStackTrace();
} finally {
try {
if (transport != null) {
transport.close();
}
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
Try using lesser secure settings in your gmail config
https://myaccount.google.com/intro/security
I'm trying to use an inline image in my thymeleaf template. Followed by this manual http://www.thymeleaf.org/doc/articles/springmail.html
For unknown reason image is not sent, i also didn't get any errors.
in template:
<img src="image_name.png" th:src="|cid:${imageResourceName}|"/>
sending email:
#Autowired
private JavaMailSender mailSender;
#Autowired
private SpringTemplateEngine templateEngine;
#Value(value = "classpath:templates/mails/listing/images/img11.png")
private Resource logoImageResource;
public boolean sendRichEmail(String receipient, EmailType emailType) {
EmailMessageConstructor emailMessageConstructor = new EmailMessageConstructor(emailType);
String recipientAddress = receipient;
String subject = emailMessageConstructor.getEmailTopic();
String from = "no-reply#xxx.com";
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = null;
try {
helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
final Context ctx = new Context();
ctx.setVariable("name", "User1");
ctx.setVariable("dateNow", new Date());
ctx.setVariable("dateExpired", MyUtils.addDays(new Date(), 30));
final String htmlContent = this.templateEngine.process(emailMessageConstructor.getEmailTemplate(), ctx);
mimeMessage.setContent(htmlContent, "text/html");
// Add the inline image, referenced from the HTML code as "cid:${imageResourceName}"
try {
String imageResourceName = logoImageResource.getFilename();
String imageContentType = new MimetypesFileTypeMap().getContentType(logoImageResource.getFile());
final InputStreamSource imageSource = new ByteArrayResource(IOUtils.toByteArray(logoImageResource.getInputStream()));
helper.addInline(imageResourceName, imageSource, imageContentType);
} catch (IOException e) {
e.printStackTrace();
}
helper.setTo(new InternetAddress(recipientAddress));
helper.setSubject(subject);
try {
helper.setFrom(new InternetAddress(from, "xxx"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
mailSender.send(mimeMessage);
} catch (MessagingException e) {
logger.error("Message creation exception: "+e.getMessage());
}
return true;
}
Want to use the image located in
/resources/templates/mails/listing/images/img11.png
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;
}
}
I have written a code to send mail through SMTP, The mail is sent from android ICS devices, but from Gingerbread device mail is not sent.
Can anyone go through the code and help me...
Firstly I m calling sendmail() method of GMailOauthSender class.
class GMailOauthSender {
private Session session;
public SMTPTransport connectToSmtp(String host, int port,
String userEmail, String oauthToken, boolean debug)
throws Exception {
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
props.put("mail.smtp.sasl.enable", "false");
session = Session.getInstance(props);
session.setDebug(debug);
final URLName unusedUrlName = null;
SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
// If the password is non-null, SMTP tries to do AUTH LOGIN.
final String emptyPassword = null;
transport.connect(host, port, userEmail, emptyPassword);
byte[] response = String.format("user=%s\1auth=Bearer %s\1\1",
userEmail, oauthToken).getBytes();
response = BASE64EncoderStream.encode(response);
transport.issueCommand("AUTH XOAUTH2 " + new String(response), 235);
return transport;
}
public synchronized void sendMail(String subject, String body,
String user, String oauthToken, String recipients, String cc) {
try {
spinner = ProgressDialog.show(FeedbackActivity.this, "",
getResources().getString(R.string.sending_mail), false, true);
new SendMailTask().execute(subject, body, user, oauthToken,
recipients, cc);
} catch (Exception e) {
Log.d("exception inside send mail method", e.toString());
}
}
class SendMailTask extends AsyncTask<Object, Object, Object> {
#Override
protected Object doInBackground(Object... params) {
String subject = (String) params[0];
String body = (String) params[1];
String user = (String) params[2];
String oauthToken = (String) params[3];
String recipients = (String) params[4];
String cc = (String) params[5];
try {
SMTPTransport smtpTransport = connectToSmtp(
"smtp.gmail.com", 587, user, oauthToken, false);
for(int i = 0; i< attachedFiles.size(); i++){
File file = new File(attachedFiles.get(i).getFilePath());
addAttachment(multipart, file);
}
MimeMessage message = new MimeMessage(session);
message.setSender(new InternetAddress(user));
message.setSubject(subject);
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(body + "\nThanks\n"+user+"\n\n"+getResources().getString(R.string.signature_text));
multipart.addBodyPart(mbp1);
message.setContent(multipart);
if (recipients.indexOf(',') > 0){
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipients));
}else{
message.setRecipient(Message.RecipientType.TO,
new InternetAddress(recipients));
}
if(cc != null && cc.length() >0){
if (cc.indexOf(',') > 0){
message.addRecipients(Message.RecipientType.CC,
InternetAddress.parse(cc));
}else{
message.addRecipient(Message.RecipientType.CC,
new InternetAddress(cc));
}
}
smtpTransport.sendMessage(message,
message.getAllRecipients());
spinner.dismiss();
finish();
return new Object[] { smtpTransport, message };
} catch (Exception e) {
spinner.dismiss();
finish();
}
return null;
}
#Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
if(result != null){
Toast.makeText(FeedbackActivity.this, getResources().getString(R.string.mail_sent), Toast.LENGTH_LONG).show();
}else{
Toast.makeText(FeedbackActivity.this, getResources().getString(R.string.mail_not_sent), Toast.LENGTH_LONG).show();
}
}
}
}