本文介绍了在Android中使用Java邮件的HTML格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用android中的Java邮件实现HTML格式的邮件.我想得到这样的结果:

I am trying to implement an HTML format mail using the Java mail in android. I would like to get results like this:

当我在GMAIL中查看从监视发送的html格式时.我没有看到任何链接,但是只有这种格式:

When I look at the html format sent from lookout in my GMAIL. I don't see any link, but just has this format:

 [image: Lookout_logo]
 [image: Signal_flare_icon] Your battery level is really low, so we located

具有信号光斑的设备.

我正在尝试以下操作:

                    Properties props = System.getProperties();
        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");

        javax.mail.Session session = javax.mail.Session.getDefaultInstance(props, null);
        MimeMessage 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]);
        }

        message.setRecipients(Message.RecipientType.BCC, toAddress);

        message.setSubject(sub);
        //message.setText(body);
                    body = "<!DOCTYPE html><html><body><img src=\"http://en.wikipedia.org/wiki/Krka_National_Park#mediaviewer/File:Krk_waterfalls.jpg\">";
        message.setContent(body, "text/html; charset=utf-8");

        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

当我查看以上代码发送的html格式时.我得到以下信息:

When I look at the html format sent with the above code. I get the following:

<!DOCTYPE html><html><body><img src="http://en.wikipedia.org/wiki/Krka_National_Park#mediaviewer/File:Krk_waterfalls.jpg>

如何确保用户将看不到任何HTML代码或URL链接(如LOOKOUT发送的邮件)?

How to make sure the user will not be able to see any html code or URL link like the mail sent by LOOKOUT?

谢谢!

推荐答案

在大多数情况下,将messageBody设置为text/html的效果很好.有点困惑为什么它不适合您的情况.

Setting messageBody as text/html works perfectly in most of the context. Little confusing why it's not working with your case.

在这里,我将通过email在android中发送html内容,以此来使您动起来.有两个方面是android中最常用于通过电子邮件发送contents的一面,其中您已经在使用其中之一.我正在向您展示与其他人的相处方式.

Hereby I'm attaching the way to get you move with sending html content with your email inside android. There are two side which are most commonly used in android for emailing contents, out of them you are already using one of them. I'm showing you the way with other one.

Mail.java :用于设置邮件配置的属性

Mail.java : Used to setting properties for your mail configuration

import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import android.text.Spanned;


public class Mail extends javax.mail.Authenticator {
private String _user;
private String _pass;

private String[] _to;
public String[] getTo() {
return _to;
}

public void setTo(String[] _to) {
    this._to = _to;
}

private String _from;

  public String getFrom() {
    return _from;
}

public void setFrom(String _from) {
    this._from = _from;
}

private String _port;
  private String _sport;

  private String _host;

  private String _subject;
  public String getSubject() {
    return _subject;
}

public void setSubject(String _subject) {
    this._subject = _subject;
}

private String _body;

  private boolean _auth;

  private boolean _debuggable;

  private Multipart _multipart;


  public Mail() {
    _host = "smtp.gmail.com"; // default smtp server
    _port = "465"; // default smtp port
    _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 Mail(String user, String pass) {
    this();

    _user = user;
    _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(RecipientType.TO, addressTo);

      msg.setSubject(_subject);
      msg.setSentDate(new Date());

      // setup message body
      BodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setContent(_body,"text/html");
      _multipart.addBodyPart(messageBodyPart);

      // Put parts in message
      msg.setContent(_multipart);

      // send email
      Transport.send(msg);

      return true;
    } else {
      return false;
    }
  }

  public void addAttachment(String filename) throws Exception {
    BodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);

    _multipart.addBodyPart(messageBodyPart);
  }

  @Override
  public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(_user, _pass);
  }

  private Properties _setProperties() {
    Properties props = new Properties();

    props.put("mail.smtp.host", _host);

    if(_debuggable) {
      props.put("mail.debug", "true");
    }

    if(_auth) {
      props.put("mail.smtp.auth", "true");
    }

    props.put("mail.smtp.port", _port);
    props.put("mail.smtp.socketFactory.port", _sport);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    return props;
  }

  // the getters and setters
  public String getBody() {
    return _body;
  }

  public void setBody(String _body) {
    this._body = _body;
  }

public void setBody(Spanned fromHtml) {
    // TODO Auto-generated method stub
    this._body=_body;
}

  // more of the getters and setters …..
}

这是在活动或片段中使用它的方式.使用new MailTask(this).execute(); //use getActivity() inside fragments

Here's how you can use it inside your activity or fragment. call using new MailTask(this).execute(); //use getActivity() inside fragments

String username,password,sentto;// add your relevant username and password and sento
public class MailTask extends AsyncTask<String,Void,String>{
        public Context context;
        public ProgressDialog pDialog;
        public MailTask(Context c)
        {
            context = c;
        }
        @Override
        protected String doInBackground(String... params) {
            /*
             * MAIL SENDING
             */
             Mail m = new Mail(username, password);
              String[] toArr = {sentto};
              m.setTo(toArr);
              m.setFrom(username);
              m.setSubject("Place Order | Rajvi Designing Application from an Android device.");
//            m.setBody("<html><body><b><p>Dear Sir,"
//                  + "  Following are the details added on Portfolio Application."
//                  + "  Name:"+ _name +"  Contact No:"+_contact +"  Address:"+_address+"</p><p> These is autogenerated mail. </p></b></body></html>");

              m.setBody("<html><body>"+MailBody.getBody(_name,_contact,_address,_orderdate)+"</body></html>");
              try {
                  if(compressedPath!=null && compressedPath.length() > 0)
                m.addAttachment(compressedPath);
                if(m.send()) {
                    Log.e("MailApp", "Mail sent successfully!");
                } else {
                    Log.e("MailApp", "Could not send email");
                }
              } catch(Exception e) {
                //Toast.makeText(MailApp.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show();
                Log.e("MailApp", "Could not send email", e);
              }
            return "MailSent";
        }
        @Override
        protected void onPostExecute(String result) {
//          Toast.makeText(HomeActivity.this, "Mail Sent", Toast.LENGTH_SHORT).show();
            CustomToast.showToastMessage(PlaceOrderActivity.this, "Mail Sent");
//          submit.setEnabled(true);
//          submit.setText("Submit");
            pDialog.dismiss();
            clear();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(context);
            pDialog.setMessage("Sending...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
    }

附加HTML内容仅供参考 Mailbody.java :用于为您的电子邮件内容生成HTML内容

Attaching HTML content just for referenceMailbody.java : Used to generate HTML contents for your email contents

public class MailBody {

    public static String getBody(String name,String contact,String address)
    {
        String str=null;

        str="<td style=\"padding:40px 20px;\" id=\"yui_3_13_0_ym1_1_1392534689432_2560\">\n" +
                "\t\t\t\t<table width=\"600\" cellpadding=\"0\" cellspacing=\"0\" id=\"yui_3_13_0_ym1_1_1392534689432_2559\">\n" +
                "\t\t\t\t\t<tbody id=\"yui_3_13_0_ym1_1_1392534689432_2558\"><tr id=\"yui_3_13_0_ym1_1_1392534689432_2600\">\n" +
                "\t\t\t\t\t\t<td align=\"left\" bgcolor=\"#272727\" style=\"padding:20px 10px;\" id=\"yui_3_13_0_ym1_1_1392534689432_2599\">\n" +
                "\t\t\t\t\t\t\t<a rel=\"nofollow\" target=\"_blank\" href=\"https://www.mailkitchen.com\" id=\"yui_3_13_0_ym1_1_1392534689432_2604\">\n" +
                "\t\t\t\t\t\t\t\t<img src=\"https://www.mailkitchen.com/images/logo-mk-en.png\" alt=\"MailKitchen\" title=\"MailKitchen\" border=\"0\" width=\"160\" height=\"30\" id=\"yui_3_13_0_ym1_1_1392534689432_2603\">\n" +
                "\t\t\t\t\t\t\t</a>\n" +
                "\t\t\t\t\t\t</td>\n" +
                "\t\t\t\t\t</tr>\n" +
                "\t\t\t\t\t<tr id=\"yui_3_13_0_ym1_1_1392534689432_2557\">\n" +
                "\t\t\t\t\t\t<td align=\"left\" bgcolor=\"#FFFFFF\" style=\"color:#6F6E6E;font-size:16px;font-family:Lato, Helvetica, Arial, sans-serif;\" id=\"yui_3_13_0_ym1_1_1392534689432_2556\">\n" +
                "\t\t\t\t\t\t\t<p align=\"center\" style=\"margin:30px 30px 0;\" id=\"yui_3_13_0_ym1_1_1392534689432_2555\">\n" +
                "\t\t\t\t\t\t\t\t Dear <span style=\"color:#A7CA01;font-size:26px;\" id=\"yui_3_13_0_ym1_1_1392534689432_2597\"> "+ name +",</span>\n" +
                "\t\t\t\t\t\t\t\t<br><br>\n" +
                "\t\t\t\t\t\t\t\t<b>Welcome to <span style=\"color:#A7CA01;\">R</span>ajvi Designing</b><br>\n" +
                "\t\t\t\t\t\t\t\t<b>and thank you for signing up on our Rajvi Designing Android Platform!</b>\n" +
                "\t\t\t\t\t\t\t</p>\n" +
                "\t\t\t\t\t\t\t<p style=\"margin:20px 30px 0;text-indent:20px;\">\n" +
                "\t\t\t\t\t\t\t\tLots of new features will be added in the coming weeks for creating, sending and tracking your Portfolio - so stay tuned!<br>\n" +
                "\t\t\t\t\t\t\t\tFrom time to time, we will send you a newsletter keeping you updated on our activities, new functionalities and features of our software suite.\n" +
                "\t\t\t\t\t\t\t</p>\n" +
                "\t\t\t\t\t\t\t<p style=\"margin:20px 30px 0;text-indent:20px;\">\n" +
                "\t\t\t\t\t\t\t\t\n" +
                "\t\t\t\t\t\t\t</p>\n" +
                "\t\t\t\t\t\t\t<ul style=\"margin:20px 30px 0 60px;padding:0;color:#A7CA01;\">\n" +
                "\t\t\t\t\t\t\t\t<li>\n" +
                "\t\t\t\t\t\t\t\t\tName :<a rel=\"nofollow\" target=\"_blank\" href=\"https://mail.mailkitchen.com/modeles/aide/mk.download.php?langue=en&amp;guide=2\" style=\"color:#A7CA01;text-decoration:none;\">"+name+"</a>\n" +
                "\t\t\t\t\t\t\t\t</li>\n" +
                "\t\t\t\t\t\t\t\t<li>\n" +
                "\t\t\t\t\t\t\t\t\tContact :<a rel=\"nofollow\" target=\"_blank\" href=\"https://mail.mailkitchen.com/modeles/aide/mk.download.php?langue=en&amp;guide=3\" style=\"color:#A7CA01;text-decoration:none;\">"+contact+"</a>\n" +
                "\t\t\t\t\t\t\t\t</li>\n" +
                "\t\t\t\t\t\t\t\t<li>\n" +
                "\t\t\t\t\t\t\t\t\tAddress :<a rel=\"nofollow\" target=\"_blank\" href=\"https://mail.mailkitchen.com/modeles/aide/mk.download.php?langue=en&amp;guide=6\" style=\"color:#A7CA01;text-decoration:none;\">"+address+"</a>\n" +
                "\t\t\t\t\t\t\t\t</li>\n" +
                "\t\t\t\t\t\t\t</ul>\n" +
                "\t\t\t\t\t\t\t<p align=\"center\" style=\"margin:20px 30px 30px;\">\n" +
                "\t\t\t\t\t\t\t\t<b>We wish you beautiful email campaigns!</b>\n" +
                "\t\t\t\t\t\t\t\t<br><br><br>\n" +
                "\t\t\t\t\t\t\t\t<b><i><span style=\"color:#A7CA01;\">(</span> <span style=\"color:#A7CA01;\">R</span>ajvi Designing Team <span style=\"color:#A7CA01;\">)</span></i></b>\n" +
                "\t\t\t\t\t\t\t</p>\n" +
                "\t\t\t\t\t\t</td>\n" +
                "\t\t\t\t\t</tr>\n" +
                "\t\t\t\t\t<tr>\n" +
                "\t\t\t\t\t\t<td align=\"center\" bgcolor=\"#EDEDED\" style=\"color:#6F6E6E;font-size:9px;font-family:Lato, Helvetica, Arial, sans-serif;padding:10px;\">\n" +
                "\t\t\t\t\t\t\tThis email has been sent by <a rel=\"nofollow\" target=\"_blank\" href=\"https://www.mailkitchen.com/\" style=\"text-decoration:underline;color:#A7CA01;\">Rajvi Design</a>, an Online Email Marketing Platform for Rajvi Design by Vikalp.<br>\n" +
                "\t\t\t\t\t\t\tPlease contact our customer service if you think that you’ve received this email by mistake.\n" +
                "\t\t\t\t\t\t</td>\n" +
                "\t\t\t\t\t</tr>\n" +
                "\t\t\t\t\t<tr>\n" +
                "\t\t\t\t\t\t<td bgcolor=\"#272727\" style=\"padding:10px;\">\n" +
                "\t\t\t\t\t\t\t<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">\n" +
                "\t\t\t\t\t\t\t\t<tbody><tr>\n" +
                "\t\t\t\t\t\t\t\t\t<td width=\"30%\" align=\"right\" style=\"padding-right:10px;border-right:2px solid #4E4E4E;\">\n" +
                "\t\t\t\t\t\t\t\t\t\t<a rel=\"nofollow\" target=\"_blank\" href=\"https://www.mailkitchen.com\">\n" +
                "\t\t\t\t\t\t\t\t\t\t\t<img src=\"https://www.mailkitchen.com/images/logo-mk-gris-en.png\" alt=\"MailKitchen\" title=\"MailKitchen\" border=\"0\" width=\"110\" height=\"30\">\n" +
                "\t\t\t\t\t\t\t\t\t\t</a>\n" +
                "\t\t\t\t\t\t\t\t\t</td>\n" +
                "\t\t\t\t\t\t\t\t\t<td align=\"left\" style=\"padding-left:10px;color:#6F6E6E;font-size:12px;font-family:Lato, Helvetica, Arial, sans-serif;\">\n" +
                "\t\t\t\t\t\t\t\t\t\tRajvi<span style=\"color:#A7CA01;\">D </span>esign<span style=\"color:#FFFFF;\"> (079) 66154709</span> <br>\n" +
                "\t\t\t\t\t\t\t\t\t\t3,Near Giriraj 2 Near Vageshwari Bus Stop, Gopal Nagar Railway Station Road, Chandlodiya, Ahmedabad - 382481" +
                "\t\t\t\t\t\t\t\t\t</td>\n" +
                "\t\t\t\t\t\t\t\t</tr>\n" +
                "\t\t\t\t\t\t\t</tbody></table>\n" +
                "\t\t\t\t\t\t</td>\n" +
                "\t\t\t\t\t</tr>\n" +
                "\t\t\t\t</tbody></table>\n" +
                "\t\t\t</td>";

        return str;
    }

这篇关于在Android中使用Java邮件的HTML格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 10:52