6

I am working on Android Webview of a website. I have include mailto for Contact and Email to a Friend. The code snippet at web side:

For Contact: <a href="mailto:[email protected]">[email protected]</a>

For Email to a Friend: <a href="mailto:?subject=Check out this product&amp;body=I found this awesome product%20http://www.example.com/product-detail/61/" title="Email to a Friend" class=""><span>Email to a Friend</span></a>

I include the following code snippet for the Android side at shouldOverrideUrlLoading method:

@Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if( url.startsWith("http:") || url.startsWith("https:") ) {
            return false;
        }

        else if (url.startsWith("tel:")) {
            Intent tel = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
            startActivity(tel);
            return true;
        }
        else if(url.startsWith("mailto:")) {
            MailTo mailTo = MailTo.parse(url);
            String emailAddress = mailTo.getTo();
            String subject = mailTo.getSubject();
            String body = mailTo.getBody();
            String cc = mailTo.getCc();
            Intent mail = new Intent(Intent.ACTION_SEND,Uri.parse(url));
            mail.setType("application/octet-stream");
            mail.putExtra(Intent.EXTRA_EMAIL, new String[]{emailAddress});
            mail.putExtra(Intent.EXTRA_SUBJECT, subject);
            mail.putExtra(Intent.EXTRA_TEXT, body);
            mail.putExtra(Intent.EXTRA_CC, cc);
            startActivity(mail);
            return true;
        }
        return false;
    }

This is working fine with Contact. But, it does not working with Email to a Friend. There is blank in Subject and Composed email field, but field To include /product-detail/105/ which must be blank. When i open website in browser in mobile it works fine. So, what should i need to do in above code for webview to handle this issue ? What can be done to solve this ?

4
  • Did you tried this mail.setType("message/rfc822"); .If not try this instead of mail.setType("application/octet-stream"); Commented Nov 22, 2016 at 6:08
  • I have use this already: mail.setType("application/octet-stream");. See in the above snippet. How do i handle multiple mailto ? Commented Nov 22, 2016 at 6:10
  • I suggested you to try this mail.setType("message/rfc822"); Commented Nov 22, 2016 at 6:15
  • I don't know but this does not work. Commented Nov 22, 2016 at 6:24

2 Answers 2

22

I solve my issue by using this :

 public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.startsWith("tel:")) {
            Intent tel = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
            startActivity(tel);
            return true;
        }
        else if (url.contains("mailto:")) {
             view.getContext().startActivity(
                    new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;

        }else {       
            view.loadUrl(url);
            return true;
        }
    }
1
  • 1
    In my case it is not needed to handle tel: separately. This view.getContext().startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url))); correctly handles both mailto: and tel: too.
    – mikep
    Commented Jun 9, 2022 at 11:03
0

for Java

public class MainActivity extends AppCompatActivity {
private Context mContext;
private Activity mActivity;

private WebView mWebView;
private TextView mTextView;


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

    // Get the application context
    mContext = getApplicationContext();
    mActivity = MainActivity.this;

    // Get the widget reference from xml layout
    mWebView = findViewById(R.id.web_view);
    mTextView = findViewById(R.id.text_view);

    // Toast the current api level
    Toast.makeText(mContext,"API LEVEL: "+Build.VERSION.SDK_INT,Toast.LENGTH_SHORT).show();

    // Set the web view client
    mWebView.setWebViewClient(new WebViewClient(){

        // For api level below 24
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url){
            Toast.makeText(mContext, "Old Method",Toast.LENGTH_SHORT).show();

            if(url.startsWith("http")){
                Toast.makeText(mContext,"Page link",Toast.LENGTH_SHORT).show();
                // Return false means, web view will handle the link
                return false;
            }else if(url.startsWith("mailto")){
                // Handle the mailto link
                handleMailToLink(url);

                // Return true means, leave the current web view and handle the url itself
                return true;
            }

            return false;
        }

        // From api level 24
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request){
            Toast.makeText(mContext, "New Method",Toast.LENGTH_SHORT).show();

            // Get the mailto url
            String url = request.getUrl().toString();

            if(url.startsWith("http")){
                Toast.makeText(mContext,"Page link",Toast.LENGTH_SHORT).show();
                // Return false means, web view will handle the link
                return false;
            }else if(url.startsWith("mailto")){
                // Handle the mailto link
                handleMailToLink(url);

                // Return true means, leave the current web view and handle the url itself
                return true;
            }

            return false;
        }
    });

    // Load the url into web view
    mWebView.loadUrl("http://www.rapidtables.com/web/html/mailto.htm");
}


/*
    Variables in mailto links:
        mailto: recipient, or recipients, separate with comma
        &cc= cc recipient(s)
        &bcc= bcc recipient(s)
        &subject= mail subject
        &body= mail body
*/

// Custom method to handle web view mailto link
protected void handleMailToLink(String url){
    // Initialize a new intent which action is send
    Intent intent = new Intent(Intent.ACTION_SENDTO);

    // For only email app handle this intent
    intent.setData(Uri.parse("mailto:"));

    // Empty the text view
    mTextView.setText("");

    // Extract the email address from mailto url
    String to = url.split("[:?]")[1];
    if(!TextUtils.isEmpty(to)){
        String[] toArray = to.split(";");
        // Put the primary email addresses array into intent
        intent.putExtra(Intent.EXTRA_EMAIL,toArray);
        mTextView.append("TO : " + to);
    }

    // Extract the cc
    if(url.contains("cc=")){
        String cc = url.split("cc=")[1];
        if(!TextUtils.isEmpty(cc)){
            //cc = cc.split("&")[0];
            cc = cc.split("&")[0];
            String[] ccArray = cc.split(";");
            // Put the cc email addresses array into intent
            intent.putExtra(Intent.EXTRA_CC,ccArray);
            mTextView.append("\nCC : " + cc );
        }
    }else {
        mTextView.append("\n" + "No CC");
    }

    // Extract the bcc
    if(url.contains("bcc=")){
        String bcc = url.split("bcc=")[1];
        if(!TextUtils.isEmpty(bcc)){
            //cc = cc.split("&")[0];
            bcc = bcc.split("&")[0];
            String[] bccArray = bcc.split(";");
            // Put the bcc email addresses array into intent
            intent.putExtra(Intent.EXTRA_BCC,bccArray);
            mTextView.append("\nBCC : " + bcc );
        }
    }else {
        mTextView.append("\n" + "No BCC");
    }

    // Extract the subject
    if(url.contains("subject=")){
        String subject = url.split("subject=")[1];
        if(!TextUtils.isEmpty(subject)){
            subject = subject.split("&")[0];
            // Encode the subject
            try{
                subject = URLDecoder.decode(subject,"UTF-8");
            }catch (UnsupportedEncodingException e){
                e.printStackTrace();
            }
            // Put the mail subject into intent
            intent.putExtra(Intent.EXTRA_SUBJECT,subject);
            mTextView.append("\nSUBJECT : " + subject );
        }
    }else {
        mTextView.append("\n" + "No SUBJECT");
    }

    // Extract the body
    if(url.contains("body=")){
        String body = url.split("body=")[1];
        if(!TextUtils.isEmpty(body)){
            body = body.split("&")[0];
            // Encode the body text
            try{
                body = URLDecoder.decode(body,"UTF-8");
            }catch (UnsupportedEncodingException e){
                e.printStackTrace();
            }
            // Put the mail body into intent
            intent.putExtra(Intent.EXTRA_TEXT,body);
            mTextView.append("\nBODY : " + body );
        }
    }else {
        mTextView.append("\n" + "No BODY");
    }

    // Email address not null or empty
    if(!TextUtils.isEmpty(to)){
        if(intent.resolveActivity(getPackageManager())!=null){
            // Finally, open the mail client activity
            startActivity(intent);
        }else {
            Toast.makeText(mContext,"No email client found.",Toast.LENGTH_SHORT).show();
        }
    }

}

}

for kotlin

private var mActivityRef: WeakReference<Activity>? = null
        override fun shouldOverrideUrlLoading(view: WebView?, request: 
         WebResourceRequest?): Boolean {
          //If you have url then you can use that otherwise get url from selected url from website
            if (request!!.url.toString().startsWith("mailto:")) {
                val activity: Activity? = mActivityRef!!.get()
                if (activity != null) {
                    val mt = MailTo.parse(request.url.toString())
                    val i: Intent = newEmailIntent( mt.to, mt.getSubject(), mt.getBody(), mt.getCc() )
                    activity.startActivity(i)
                    view!!.reload()
                    return true
                }
            } else {
                view!!.loadUrl(request.url.toString())
            }
            return true
        }

    }


}
 private fun newEmailIntent(address: String, subject: String, body: String, cc: String): Intent {
    val intent = Intent(Intent.ACTION_SEND)
    intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(address))
    intent.putExtra(Intent.EXTRA_TEXT, body)
    intent.putExtra(Intent.EXTRA_SUBJECT, subject)
    intent.putExtra(Intent.EXTRA_CC, cc)
    intent.type = "message/rfc822"
    return intent
}

reference link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.