SilleBille
SilleBille

Reputation: 639

can't send mail using android code

I am trying to send a mail within application. I'm not gonna pop up any interactions with user. I have two java codes.

MainActivity.java

package com.example.test;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
public static String EXTRA_MESSAGE = "com.example.MESSAGE";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);

}

public void sendMessage(View view)
{
    try {   
        test sender = new test();
        sender.send();
        Toast.makeText(getApplicationContext(), "Message Sent!!! :)", Toast.LENGTH_LONG).show();
    } catch (Exception e) {   
        //Log.e("SendMail", e.getMessage(), e);   
    } 
}

public void exit(View view)
{
    System.exit(0);
}    
}

test.java

package com.example.test;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

import android.widget.Toast;

public class test extends MainActivity
{
public void send()
{
    String host = "smtp.gmail.com";
String from = "MYUSERNAME";
String pass = "MYPASS";
try
{
Properties props = new Properties();
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 = {"[email protected]"}; // added this line

Session session = Session.getDefaultInstance(props, null);
Message message = new MimeMessage(session);
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++ ) { // changed from a while loop
    toAddress[i] = new InternetAddress(to[i]);
}
System.out.println(Message.RecipientType.TO);

for( int i=0; i < toAddress.length; i++) { // changed from a while loop
    message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject("This is subject");
message.setText("Welcome to your mail");
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch(Exception e)
{
    Toast.makeText(getApplicationContext(), "Error" + e, Toast.LENGTH_LONG).show();
}
}
}

I can't send mail when i press the send button. I have invoked the sendMessage() using xml onClick.

There are NO ERRORS in eclipse. The project compiles, installs but i don't receive the mail. When i try with just the java using javac and run the test.java, it works FINE. I get mail in my account.

Thanks for helping me.

Upvotes: 0

Views: 236

Answers (3)

Federico Perez
Federico Perez

Reputation: 1026

I havent tried your send code but the way you are getting the context will raise a null pointer.

A NullPointerException is probably raised in getApplicationContext() in the Toast.makeText(getApplicationContext(), "Error" + e, Toast.LENGTH_LONG).show(); line. You shouldnt extend an activity to get the Context. Pass the context to the Test class using a constructor instead.

For example:

public class Test {
    private Context cntxt;

    public Test(Context context){
        this.cntxt = context;
    }
    public void send() {
        //Code to send
        //And when you need the context you use the cntxt
        Toast.makeText(cntxt, "Error" + e, Toast.LENGTH_LONG).show()
    }
}

Also remember that is a good practice and convention to declare classes names starting with capital letters. You should rename test to Test.

Upvotes: 0

nomachinez
nomachinez

Reputation: 521

Do you have

<uses-permission android:name="android.permission.INTERNET" />

In your applications manifest file?

Edit 1:

How about changing

Session session = Session.getDefaultInstance(props, null);

to

Session session = Session.getDefaultInstance(props, new MailAuthenticator(from, pass));

Upvotes: 0

NagarjunaReddy
NagarjunaReddy

Reputation: 8645

just use like this code

            Intent i = new Intent(Intent.ACTION_SEND);

                        i.setType("message/rfc822");
                        i.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]" });
                        i.putExtra(Intent.EXTRA_SUBJECT, headline);
                        i.putExtra(Intent.EXTRA_TEXT, source);
                        try {
                            activity.startActivity(Intent.createChooser(i,"Send mail..."));
                        } catch (android.content.ActivityNotFoundException ex) {
                        }

Upvotes: 1

Related Questions