我正在尝试使用Android中的Java邮件实现HTML格式的邮件。我想得到这样的结果:
当我查看我的GMAIL中的了望台发送的html格式时。我没有看到任何链接,但只有这种格式:
[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格式时。我得到以下内容:
<!DOCTYPE html><html><body><img src="http://en.wikipedia.org/wiki/Krka_National_Park#mediaviewer/File:Krk_waterfalls.jpg>
如何确保用户无法查看任何html代码或URL链接,例如LOOKOUT发送的邮件?
谢谢!
答案 0 :(得分:1)
将messageBody
设置为text/html
可在大多数情况下完美运行。很难混淆为什么它不适合你的情况。
因此,我正在通过发送html
内容与您的email
内部安卓程序一起使用。 android中有两个最常用的电子邮件用于发送电子邮件contents
,其中你已经使用其中一个。我正在向你展示其他人的方式。
Mail.java :用于设置邮件配置的属性
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
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内容
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;
}
答案 1 :(得分:0)
您可以简化对message.setText的setContent调用(body,&#34; html&#34;,&#34; utf-8&#34;); 除此之外,我不明白你的问题是什么。听起来你正好看到了你发送的html。如果你想看到不同的东西,发送不同的东西。或者是你的邮件阅读器中没有正确显示html的问题?如果要复制顶部的示例消息显示,则需要查看消息中的实际html代码。使用&#34;显示为原始&#34; Gmail中的选项。
答案 2 :(得分:0)
为什么你不能使用HtmlEmail?
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
和
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();
参考 http://www.mysamplecode.com/2012/09/send-html-email-in-java-using-url-as.html了解更多信息。
答案 3 :(得分:0)
您需要发送包含2种不同内容类型的多部分电子邮件:
我已在"Why Multi-Part Email is Important"下贴了一个示例(由Litmus发布电子邮件的人{{}}发布),这应该会有所帮助
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--