I am trying to send an email programmatically, from a microsoft exchange account. is this possible through the imap protocol, if so how, i cant find any guide on this. Or do i need to use the smtp for this.
what i tried so far:
public MailSender() {
host = "smtp.gmail.com"; // default smtp server
hunterHost = "exchange.ictum.nl";
port = "465"; // default smtp port
hunterPort = "587";
sport = "465"; // default socketfactory port
user = ""; // username
pass = ""; // password
from = ""; // email sent from
subject = ""; // email subject
body = ""; // email body
debuggable = false; // debug mode on or off - default off
auth = true; // smtp authentication - default on
multipart = new MimeMultipart();
// There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added.
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);
}
public MailSender(String user, String pass) {
this();
this.user = user;
this.pass = pass;
}
public boolean send() throws Exception {
Properties props = _setProperties();
if (!user.equals("") && !pass.equals("") && to.length > 0 && !from.equals("") && !subject.equals("") && !body.equals("")) {
Session session = Session.getInstance(props, this);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] addressTo = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++) {
addressTo[i] = new InternetAddress(to[i]);
}
msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
msg.setSubject(subject);
msg.setSentDate(new Date());
// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(body);
multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(multipart);
// send email
Transport.send(msg);
return true;
} else {
return false;
}
}
public void addAttachment(String fileLocation, String fileName) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileLocation);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileLocation);
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass);
}
private Properties _setProperties() {
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "imaps");
props.setProperty("mail.imaps.host", hunterHost);
props.put("mail.imaps.user", user);
props.put("mail.imaps.host", hunterHost);
props.put("mail.imaps.auth", "true");
props.put("mail.imaps.port", hunterPort);
props.put("mail.imaps.socketFactory.port", hunterPort);
props.put("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.imaps.socketFactory.fallback", "false");
props.setProperty("mail.imaps.quitwait", "false");
return props;
}
}
i call it like: public class MailHandler { private static final String TAG = MailHandler.class.getSimpleName(); private Activity activity; private MailSender mailSender;
public MailHandler(Activity activity) {
this.activity = activity;
}
public void mail(Mail mail) {
mailSender = new MailSender("oscar@*****-***.com", "*******");
mailSender.setTo(mail.getTo());
mailSender.setFrom(mail.getFrom());
mailSender.setSubject(mail.getSubject());
mailSender.setBody(mail.getBody());
instantMailTask instantMailTask = new instantMailTask();
instantMailTask.execute();
}
private class instantMailTask extends AsyncTask<Void, Bitmap, Bitmap> {
@Override
protected void onPreExecute() {
super.onPreExecute();
ReceiptHandler receiptHandler = new ReceiptHandler(activity);
//TODO get company name and contact info programmatically
String body = "Hunter - CRM \n";
body += receiptHandler.createReceiptLines();
body += "\n contact" +
"\n info" +
"\n address";
generateNote("Receipt", body);
generateNote(MobileRegisterApplication.getActiveReceipt().getReceiptName(), receiptHandler.createReceiptLines());
Log.d(TAG, "onPreExecute: ");
}
@Override
protected Bitmap doInBackground(Void... params) {
Log.d(TAG, "doInBackground: ");
try {
mailSender.addAttachment(activity.getFilesDir().getPath() + "/Receipt.txt", "TryOut.txt");
if(mailSender.send()) {
Log.d("Mail", "doInBackground: Email was sent successfully.");
} else {
Log.d("Mail", "doInBackground: Email was not sent.");
}
} catch(Exception e) {
Log.e("MailApp", "Could not send email", e);
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
Log.d("Mail", "onPostExecute: ");
}
}
public void generateNote(String sFileName, String sBody) {
try {
File root = new File(activity.getFilesDir(), "Receipts");
if (!root.exists()) {
root.mkdirs();
}
FileOutputStream fos = activity.openFileOutput( sFileName +".txt",Context.MODE_PRIVATE);
Writer out = new OutputStreamWriter(fos);
out.write(sBody);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}