So I'm using the following code to create and write data into a file:
String filename1 = "transaction.txt";
String data = "The data to be sent"
try {
FileOutputStream fOs = openFileOutput(filename1,MODE_PRIVATE);
fOs.write(data.getBytes());
fOs.close();
Log.v("FILE","Files have been written");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Simple so far..
So, how do I send this file "transaction.txt" as an Attachment to and from any GMAIL account?
You can Ignore the below part if it confuses you, but, below lies code of how I use the JavaMail API to send a message:
public class MainActivity extends Activity implements OnClickListener{
Session session = null;
ProgressDialog pdialog = null;
Context context = null;
EditText reciep, sub, msg;
String rec, subject, textMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
Button login = (Button) findViewById(R.id.btn_submit);
reciep = (EditText) findViewById(R.id.et_to);
sub = (EditText) findViewById(R.id.et_sub);
msg = (EditText) findViewById(R.id.et_text);
login.setOnClickListener(this);
}
@Override
public void onClick(View v) {
rec = reciep.getText().toString();
subject = sub.getText().toString();
textMessage = msg.getText().toString();
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("XXXXX@gmail.com", "XXXXXX");
}
});
pdialog = ProgressDialog.show(context, "", "Sending Mail...", true);
RetreiveFeedTask task = new RetreiveFeedTask();
task.execute();
}
class RetreiveFeedTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try{
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("testfrom354@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(rec));
message.setSubject(subject);
message.setContent(textMessage, "text/html; charset=utf-8");
Transport.send(message);
} catch(MessagingException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
pdialog.dismiss();
reciep.setText("");
msg.setText("");
sub.setText("");
Toast.makeText(getApplicationContext(), "Message sent", Toast.LENGTH_LONG).show();
}
}
}
THIS email part is very easy actually, but I am open to changes....