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

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
your device with Signal Flare.
I was trying the following:
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();
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>
How to make sure the user will not be able to see any html code or URL link like the mail sent by LOOKOUT?
Thanks!
回答1:
Setting messageBody
as text/html
works perfectly in most of the context. Little confusing why it's not working with your case.
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 : 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 …..
}
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();
}
}
Attaching HTML content just for reference Mailbody.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&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&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&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;
}
回答2:
You can simplify the setContent call to message.setText(body, "html", "utf-8"); Other than that, I don't understand what your problem is. It sounds like you're seeing exactly the html that you're sending. If you want to see something different, send something different. Or is the problem that the html is not being displayed properly in your mail reader? If you want to copy the example message display at the top, you need to look at the actual html code in the message. Use the "Show as original" option in Gmail.
回答3:
Why you can't go for HtmlEmail?
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
and
HtmlEmail htmlEmail = new HtmlEmail();
htmlEmail.setHostName("smtp.gmail.com");
htmlEmail.setSmtpPort(587);
htmlEmail.setDebug(true);
htmlEmail.setAuthenticator(new DefaultAuthenticator("userId", "password"));
htmlEmail.setTLS(true);
htmlEmail.addTo("recipient@gmail.com", "recipient");
htmlEmail.setFrom("sender@gmail.com", "sender");
htmlEmail.setSubject("Send HTML email with body content from URI");
htmlEmail.setHtmlMsg(responseBody);
htmlEmail.send();
Refer http://www.mysamplecode.com/2012/09/send-html-email-in-java-using-url-as.html for more info.
回答4:
You need to send a multi part email with 2 different content types:
- text/plain for the text view
- text/html for the HTML view
I've pasted an example below from "Why Multi-Part Email is Important" (posted by the folks at Litmus whose business is sending emails) which should help
X-sender: <sender@sendersdomain.com>
X-receiver: <somerecipient@recipientdomain.com>
From: "Senders Name" <sender@sendersdomain.com>
To: "Recipient Name" <somerecipient@recipientdomain.com>
Message-ID: <5bec11c119194c14999e592feb46e3cf@sendersdomain.com>
Date: Sat, 24 Sep 2005 15:06:49 -0400
Subject: Sample Multi-Part
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="----=_NextPart_DC7E1BB5_1105_4DB3_BAE3_2A6208EB099D"
------=_NextPart_DC7E1BB5_1105_4DB3_BAE3_2A6208EB099D
Content-type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
Sample Text Content
------=_NextPart_DC7E1BB5_1105_4DB3_BAE3_2A6208EB099D
Content-type: text/html; charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
<html>
<head>
</head>
<body>
<div style=3D"FONT-SIZE: 10pt; FONT-FAMILY: Arial">Sample HTML =
Content</div>
</body>
</html>
------=_NextPart_DC7E1BB5_1105_4DB3_BAE3_2A6208EB099D--
来源:https://stackoverflow.com/questions/24093312/html-format-using-java-mail-in-android