0

I have created one contact us activity in my android application. It contain 4 edit text such as name, phone number, email and message along with the submit button. What i have to do is when i will click on submit button then the data from all four edit text should be E-mailed to me on my mail id. Can anyone suggest how can i do so? If any further details are required then please let me know. Thanks Here is some code sample.

                String Name = name.getText().toString();
                String Phone = phone.getText().toString();
                String Email = email.getText().toString();
                String Message = message.getText().toString();

                //check whether the msg empty or not
                if (Name.length() != 0 && Phone.length() != 0 && Email.length() != 0) {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://www.abcd.com/Server1.php");

                    try {
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                        nameValuePairs.add(new BasicNameValuePair("id", "01"));
                        nameValuePairs.add(new BasicNameValuePair("message", Name));

                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        httpclient.execute(httppost);
                        name.setText(""); //reset the message text field
                        phone.setText(""); //reset the message text field
                        email.setText(""); //reset the message text field
                        message.setText(""); //reset the message text field
                        Toast.makeText(getBaseContext(), "Sent", Toast.LENGTH_SHORT).show();
                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    //display message if text field is empty
                    Toast.makeText(getBaseContext(), "All fields are required", Toast.LENGTH_SHORT).show();
                }
            }

I have written this code. It is not giving any error. App is also not crashing but the data is not getting on email. Any Help?

public class ContactUs extends AppCompatActivity {
private EditText name, phone, email, msg;
private Button submitButton;
private TextInputLayout inputLayoutName, inputLayoutPhone, inputLayoutEmail, inputLayoutMessage;


EditText editText;


//New Code
Session session = null;
ProgressDialog pdialog = null;
Context context = null;
//private EditText name, phone, email, message;
String Name, Phone, Email, Msg;
String receiver = "xyz@gmail.com";
String sender = "abc@gmail.com";
String subject = "Test Mail";
String textMessage = "Hello To All";
String Data;

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

    initializeWidgets();


    submitButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean isValid = true;
            if (name.getText().toString().isEmpty()) {
                inputLayoutName.setError("Name is mandatory");
                isValid = false;
            } else {
                inputLayoutName.setErrorEnabled(false);
            }

            if (phone.getText().toString().isEmpty()) {
                inputLayoutPhone.setError("Phone number is mandatory");
                isValid = false;
            } else {
                inputLayoutPhone.setErrorEnabled(false);
            }

            if (email.getText().toString().isEmpty()) {
                inputLayoutEmail.setError("Email is required");
                isValid = false;
            } else {
                inputLayoutEmail.setErrorEnabled(false);
            }


            if (isValid) {
                                String Name = name.getText().toString();
                String Phone = phone.getText().toString();
                String Email = email.getText().toString();
                String Message = msg.getText().toString();

                Data = Name + Phone + Email + Message;

                Properties prop = new Properties();
                prop.put("mail.smtp.host", "smtp.gmail.com");
                prop.put("mail.smtp.socketFactory.port", "587");
                prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                prop.put("mail.smtp.auth", "true");
                prop.put("mail.smtp.port", "587");

                session = Session.getDefaultInstance(prop, new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        PasswordAuthentication passwordAuthentication = new PasswordAuthentication(sender, "abc");
                        return passwordAuthentication;
                    } });

                try {
                    MimeMessage message = new MimeMessage(session);
                    message.setFrom(new InternetAddress(sender));
                    message.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(receiver));
                    message.setText(Data);
                    Transport.send(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            name.setText("");
            phone.setText("");
            email.setText("");
            msg.setText("");
            Toast.makeText(getApplicationContext(), "Data Submitted Successfully", Toast.LENGTH_LONG).show();
        }

    });
}

private void initializeWidgets() {

    name = (EditText) findViewById(R.id.name);
    phone = (EditText) findViewById(R.id.phone);
    email = (EditText) findViewById(R.id.email);
    msg = (EditText) findViewById(R.id.message);
    submitButton = (Button) findViewById(R.id.btnSubmit);
    inputLayoutName = (TextInputLayout) findViewById(R.id.inputLayoutName);
    inputLayoutPhone = (TextInputLayout) findViewById(R.id.inputLayoutPhone);
    inputLayoutEmail = (TextInputLayout) findViewById(R.id.inputLayoutEmail);
    inputLayoutMessage = (TextInputLayout) findViewById(R.id.inputLayoutMessage);

}


public boolean onSupportNavigateUp() {
    onBackPressed();`enter code here`
    return true;
}
Fazeel Qureshi
  • 854
  • 9
  • 18
  • I have just tried to write some code to do so. But it is not working. Please something apart from the code that i have written. my aim is to send all the data on mail id when i click on submit button. – Fazeel Qureshi Jun 05 '17 at 12:23

1 Answers1

0

Here you can find a solution for sending email with intent (user action required).

You have to create a String with email body containing all data you want to send, then the Email client is opened and the user can manually send the message.

Otherwise you can use your smtp configuration sending an email in background, without user action as explained here. This way the email is sent without user knowledge, but you have to know configuration of your Email account.

Following for Gmail (copied from here):

import javax.activation.DataHandler;   
import javax.activation.DataSource;   
import javax.mail.Message;   
import javax.mail.PasswordAuthentication;   
import javax.mail.Session;   
import javax.mail.Transport;   
import javax.mail.internet.InternetAddress;   
import javax.mail.internet.MimeMessage;   
import java.io.ByteArrayInputStream;   
import java.io.IOException;   
import java.io.InputStream;   
import java.io.OutputStream;   
import java.security.Security;   
import java.util.Properties;   

public class GMailSender extends javax.mail.Authenticator {   
    private String mailhost = "smtp.gmail.com";   
    private String user;   
    private String password;   
    private Session session;   

    static {   
        Security.addProvider(new com.provider.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);   
    }   

    protected PasswordAuthentication getPasswordAuthentication() {   
        return new PasswordAuthentication(user, password);   
    }   

    public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {   
        try{
        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);   
        if (recipients.indexOf(',') > 0)   
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));   
        else  
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));   
        Transport.send(message);   
        }catch(Exception e){

        }
    }   

    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");   
        }   
    }   
}  
Christian Ascone
  • 1,117
  • 8
  • 14
  • what will be the code for email. I mean can you please suggest some code in if block – Fazeel Qureshi Jun 06 '17 at 05:42
  • Take a look at posted links. There, you'll find code to add. Choose the code based on your needs, if you prefer a background action or not – Christian Ascone Jun 06 '17 at 06:37
  • Brother have you got my point? I want the data of user filled up in contact form should be sent to an specific mail id. So who will be the sender here because the receiver is fix. – Fazeel Qureshi Jun 07 '17 at 07:13
  • You should pass `Email` instead of `receiver`. What I see is that you're sending email to "abc@gmail.com". It should look like this: ```message.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(Email));``` Let me know if I'm misunderstanding your point. – Christian Ascone Jun 07 '17 at 07:22
  • the code message.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(receiver)); was already written. I am sending the data from abc@gmail.com to xyz@gmail.com. My point is the user will be anonymous. It can fill any data in the form. When he click on submit button then the data of user should be received in mail id xyz@gmail.com. Sender can be anyone. – Fazeel Qureshi Jun 07 '17 at 07:40
  • Now I understand, my fault. If user is anonymous you have to use your private email settings for sending message (smtp, sender, pass, etc) and your email address as receiver. Your code seems good. You're not getting any exception after `Transport.send(message)`? – Christian Ascone Jun 07 '17 at 07:48
  • I edited the code. Try with this configuration and check you're not receiving messages in your SPAM. – Christian Ascone Jun 07 '17 at 08:16
  • second argument is wrong in session = Session.getDefaultInstance(props, this); and what is the value of mailhost variable? I have checked the spam folder, no mail in it. – Fazeel Qureshi Jun 07 '17 at 09:21