本文整理了Java中org.apache.commons.mail.HtmlEmail
类的一些代码示例,展示了HtmlEmail
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HtmlEmail
类的具体详情如下:
包路径:org.apache.commons.mail.HtmlEmail
类名称:HtmlEmail
[英]An HTML multipart email.
This class is used to send HTML formatted email. A text message can also be set for HTML unaware email clients, such as text-based email clients.
This class also inherits from MultiPartEmail, so it is easy to add attachments to the email.
To send an email in HTML, one should create a HtmlEmail
, then use the #setFrom(String), #addTo(String) etc. methods. The HTML content can be set with the #setHtmlMsg(String) method. The alternative text content can be set with #setTextMsg(String).
Either the text or HTML can be omitted, in which case the "main" part of the multipart becomes whichever is supplied rather than a multipart/alternative
.
It is also possible to embed URLs, files, or arbitrary DataSource
s directly into the body of the mail:
HtmlEmail he = new HtmlEmail();
File img = new File("my/image.gif");
PNGDataSource png = new PNGDataSource(decodedPNGOutputStream); // a custom class
StringBuffer msg = new StringBuffer();
msg.append("<html><body>");
msg.append("<img src=cid:").append(he.embed(img)).append(">");
msg.append("<img src=cid:").append(he.embed(png)).append(">");
msg.append("</body></html>");
he.setHtmlMsg(msg.toString());
// code to set the other email fields (not shown)
Embedded entities are tracked by their name, which for File
s is the filename itself and for URL
s is the canonical path. It is an error to bind the same name to more than one entity, and this class will attempt to validate that for File
s and URL
s. When embedding a DataSource
, the code uses the equals()
method defined on the DataSource
s to make the determination.
[中]HTML多部分电子邮件。
此类用于发送HTML格式的电子邮件。还可以为不知道HTML的电子邮件客户端(例如基于文本的电子邮件客户端)设置文本消息。
此类还继承自MultiPartEmail,因此很容易向电子邮件添加附件。
要以HTML格式发送电子邮件,应创建HtmlEmail
,然后使用#setFrom(String)、#addTo(String)等方法。可以使用#setHtmlMsg(String)方法设置HTML内容。可使用#setTextMsg(字符串)设置备选文本内容。
可以省略文本或HTML,在这种情况下,多部分的“主要”部分将变为提供的部分,而不是multipart/alternative
。
####嵌入图像和媒体
也可以将URL、文件或任意DataSource
直接嵌入邮件正文:
HtmlEmail he = new HtmlEmail();
File img = new File("my/image.gif");
PNGDataSource png = new PNGDataSource(decodedPNGOutputStream); // a custom class
StringBuffer msg = new StringBuffer();
msg.append("<html><body>");
msg.append("<img src=cid:").append(he.embed(img)).append(">");
msg.append("<img src=cid:").append(he.embed(png)).append(">");
msg.append("</body></html>");
he.setHtmlMsg(msg.toString());
// code to set the other email fields (not shown)
嵌入式实体通过名称进行跟踪,对于File
s是文件名本身,URL
s是规范路径。将同一名称绑定到多个实体是错误的,此类将尝试验证File
s和URL
s的名称。嵌入DataSource
时,代码使用DataSource
s上定义的equals()
方法进行确定。
代码示例来源:origin: stackoverflow.com
HtmlEmail email = new HtmlEmail();
email.setHostName(mailserver);
email.setAuthentication(username, password);
email.setSmtpPort(port);
email.setFrom(fromEmail);
email.addTo(to);
email.setSubject(subject);
email.setTextMsg(textBody);
email.setHtmlMsg(htmlBody);
email.setDebug(true);
email.send();
代码示例来源:origin: Activiti/Activiti
protected HtmlEmail createHtmlEmail(String text, String html) {
HtmlEmail email = new HtmlEmail();
try {
email.setHtmlMsg(html);
if (text != null) { // for email clients that don't support html
email.setTextMsg(text);
}
return email;
} catch (EmailException e) {
throw new ActivitiException("Could not create HTML email", e);
}
}
代码示例来源:origin: Dreampie/Resty
/**
* @param subject 主题
* @param body 内容
* @param attachment 附件
* @param recipients 收件人
*/
public static HtmlEmail getHtmlEmail(String subject, String body, EmailAttachment attachment, String... recipients) {
try {
HtmlEmail htmlEmail = new HtmlEmail();
configEmail(subject, htmlEmail, recipients);
if (body != null)
htmlEmail.setHtmlMsg(body);
// set the alter native message
htmlEmail.setTextMsg("Your email client does not support HTML messages");
if (attachment != null)
htmlEmail.attach(attachment);
return htmlEmail;
} catch (EmailException e) {
throw new MailException("Unabled to send email", e);
}
}
代码示例来源:origin: apache/kylin
Email email = new HtmlEmail();
email.setHostName(host);
email.setStartTLSEnabled(starttlsEnabled);
email.setCharset("UTF-8");
if (isHtmlMsg) {
((HtmlEmail) email).setHtmlMsg(content);
} else {
((HtmlEmail) email).setTextMsg(content);
logger.error(e.getLocalizedMessage(), e);
return false;
代码示例来源:origin: inspectIT/inspectIT
@Test
public void sendWithoutDefaultRecipientsAndProperties() throws Exception {
Session session = Session.getInstance(new Properties());
when(mailMock.getMailSession()).thenReturn(session);
when(objectFactoryMock.createHtmlEmail()).thenReturn(mailMock);
when(objectFactoryMock.getSmtpTransport()).thenReturn(transportMock);
verify(transportMock).connect(any(String.class), any(Integer.class), any(String.class), any(String.class));
verify(transportMock).close();
verify(mailMock).setHostName("host");
verify(mailMock).setSmtpPort(25);
verify(mailMock).setAuthentication("user", "passwd");
verify(mailMock).setFrom("sender@example.com", "Sender Name");
verify(mailMock).addTo("three@example.com");
verify(mailMock).setSubject("subject");
verify(mailMock).setHtmlMsg("htmlBody");
verify(mailMock).setTextMsg("textBody");
verify(mailMock).send();
verifyNoMoreInteractions(objectFactoryMock, transportMock, mailMock);
assertThat(session.getProperties().entrySet(), hasSize(0));
代码示例来源:origin: org.apache.commons/commons-email
@Test
public void testParseCreatedHtmlEmailWithMixedContent() throws Exception
{
final Session session = Session.getDefaultInstance(new Properties());
final HtmlEmail email = new HtmlEmail();
email.setMailSession(session);
email.setFrom("test_from@apache.org");
email.setSubject("Test Subject");
email.addTo("test_to@apache.org");
email.setTextMsg("My test message");
email.setHtmlMsg("<p>My HTML message</p>");
email.buildMimeMessage();
final MimeMessage msg = email.getMimeMessage();
final MimeMessageParser mimeMessageParser = new MimeMessageParser(msg);
mimeMessageParser.parse();
assertEquals("Test Subject", mimeMessageParser.getSubject());
assertNotNull(mimeMessageParser.getMimeMessage());
assertTrue(mimeMessageParser.isMultipart());
assertTrue(mimeMessageParser.hasHtmlContent());
assertTrue(mimeMessageParser.hasPlainContent());
assertNotNull(mimeMessageParser.getPlainContent());
assertNotNull(mimeMessageParser.getHtmlContent());
assertTrue(mimeMessageParser.getTo().size() == 1);
assertTrue(mimeMessageParser.getCc().size() == 0);
assertTrue(mimeMessageParser.getBcc().size() == 0);
assertEquals("test_from@apache.org", mimeMessageParser.getFrom());
assertEquals("test_from@apache.org", mimeMessageParser.getReplyTo());
assertFalse(mimeMessageParser.hasAttachments());
}
代码示例来源:origin: stackoverflow.com
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();
代码示例来源:origin: com.bbossgroups.pdp/pdp-cms
public void sendHtmlEmails(Map toEmails, String subject, String htmlMsg)
throws Exception {
try {
HtmlEmail email = new HtmlEmail();
this.setEmail(email, toEmails, subject, "HtmlEmail");
email.setHtmlMsg(htmlMsg);
email
.setTextMsg("Your email client does not support HTML messages");
email.send();
} catch (EmailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw e;
}
}
代码示例来源:origin: stackoverflow.com
HtmlEmail email = new HtmlEmail();
email.setSubject("<your subject>");
email.setHtmlMsg("<your html message body>");
email.setHostName("<host>");
email.setFrom("<from_address>");
email.addTo("<recipient_address>");
email.send();
代码示例来源:origin: theonedev/onedev
HtmlEmail email = new HtmlEmail();
email.setSocketConnectionTimeout(Bootstrap.SOCKET_CONNECT_TIMEOUT);
email.setSocketTimeout(mailSetting.getTimeout()*1000);
email.setStartTLSEnabled(true);
email.setSSLOnConnect(mailSetting.isEnableSSL());
email.setSSLCheckServerIdentity(false);
email.setFrom(senderEmail);
for (String address: toList)
email.addTo(address);
email.setHostName(mailSetting.getSmtpHost());
email.setSmtpPort(mailSetting.getSmtpPort());
email.setSslSmtpPort(String.valueOf(mailSetting.getSmtpPort()));
String smtpUser = mailSetting.getSmtpUser();
if (smtpUser != null)
email.setAuthentication(smtpUser, mailSetting.getSmtpPassword());
email.setCharset(CharEncoding.UTF_8);
email.setSubject(subject);
email.setHtmlMsg(body);
email.send();
} catch (EmailException e) {
throw new RuntimeException(e);
代码示例来源:origin: Junety-C/alarm
private boolean send(String title, String content, List<String> receivers) {
try {
HtmlEmail email = new HtmlEmail();
email.setAuthentication(Configuration.MAIL_SENDER_USERNAME, Configuration.MAIL_SENDER_PASSWORD);
email.setHostName(Configuration.MAIL_SENDER_SMTP_HOST);
email.setSmtpPort(Configuration.MAIL_SENDER_SMTP_PORT);
email.setFrom(Configuration.MAIL_SENDER_USERNAME, Configuration.MAIL_SENDER_NAME);
email.setSubject(title);
email.setHtmlMsg(content);
email.addTo(receivers.stream().toArray(String[]::new));
email.setCharset("UTF-8");
email.setSSLOnConnect(false);
email.send();
logger.info("send mail to {} success", JSON.toJSONString(receivers));
return true;
} catch (Exception e) {
logger.error("send mail to {} fail, caused by", JSON.toJSONString(receivers), e);
return false;
}
}
}
代码示例来源:origin: biezhi/java-library-examples
public static void main(String[] args) throws EmailException, MalformedURLException {
// 创建 Email Message
HtmlEmail email = new HtmlEmail();
email.setHostName("mail.myserver.com");
email.addTo("jdoe@somewhere.org", "John Doe");
email.setFrom("me@apache.org", "Me");
email.setSubject("Test email with inline image");
// 嵌入图片
URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
String cid = email.embed(url, "Apache logo");
// 发送 HTML 内容
email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>");
// 设置替代消息
email.setTextMsg("Your email client does not support HTML messages");
// 发送
email.send();
}
}
代码示例来源:origin: com.github.robozonky/robozonky-notifications
private HtmlEmail createNewEmail(final SessionInfo session) throws EmailException {
final HtmlEmail email = new HtmlEmail();
email.setCharset(Defaults.CHARSET.displayName()); // otherwise the e-mail contents are mangled
email.setHostName(getSmtpHostname());
email.setSmtpPort(getSmtpPort());
email.setStartTLSRequired(isStartTlsRequired());
email.setSSLOnConnect(isSslOnConnectRequired());
if (isAuthenticationRequired()) {
final String username = getSmtpUsername();
LOGGER.debug("Will contact SMTP server as '{}'.", username);
email.setAuthentication(getSmtpUsername(), getSmtpPassword());
} else {
LOGGER.debug("Will contact SMTP server anonymously.");
}
email.setFrom(getSender(), session.getName());
email.addTo(getRecipient());
return email;
}
代码示例来源:origin: apache/incubator-unomi
email.setHostName(mailServerHostName);
email.setSmtpPort(mailServerPort);
email.setAuthenticator(new DefaultAuthenticator(mailServerUsername, mailServerPassword));
email.setSSLOnConnect(mailServerSSLOnConnect);
try {
email.addTo(to);
email.setFrom(from);
if (cc != null && cc.length() > 0) {
email.addCc(cc);
email.addBcc(bcc);
email.setSubject(subject);
email.setHtmlMsg(htmlEmailTemplate);
email.setTextMsg("Your email client does not support HTML messages");
email.send();
} catch (EmailException e) {
logger.error("Cannot send mail",e);
代码示例来源:origin: stackoverflow.com
email = new HtmlEmail();
email.setAuthenticator(new DefaultAuthenticator("youremail@yahoo.com", "yourpasswordhere"));
email.setSmtpPort(587);
email.setHostName("smtp.gmail.com");
email.setDebug(true);
email.addTo(userEmail, "Whatever you want here");
email.setFrom("youremail@yahoo.com", "Your business name");
email.setSubject("Your email subject here");
email.getMailSession().getProperties().put("mail.smtps.auth", "true");
email.getMailSession().getProperties().put("mail.debug", "true");
email.getMailSession().getProperties().put("mail.smtps.port", "587");
email.getMailSession().getProperties().put("mail.smtps.socketFactory.port", "587");
email.getMailSession().getProperties().put("mail.smtps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
email.getMailSession().getProperties().put("mail.smtps.socketFactory.fallback", "false");
email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
代码示例来源:origin: dhis2/dhis2-core
private HtmlEmail getHtmlEmail( String hostName, int port, String username, String password, boolean tls,
String sender ) throws EmailException
{
HtmlEmail email = new HtmlEmail();
email.setHostName( hostName );
email.setFrom( sender, getEmailName() );
email.setSmtpPort( port );
email.setStartTLSEnabled( tls );
if ( username != null && password != null )
{
email.setAuthenticator( new DefaultAuthenticator( username, password ) );
}
return email;
}
代码示例来源:origin: mycontroller-org/mycontroller
public static void sendSimpleEmail(String emails, String subject, String message, boolean initializeEmail)
throws EmailException {
if (initializeEmail) {
initializeEmail(AppProperties.getInstance().getEmailSettings());
}
email.setCharset("UTF-8");
email.setSubject(subject);
email.setHtmlMsg(message);
email.addTo(emails.split(","));
String sendReturn = email.send();
_logger.debug("Send Status:[{}]", sendReturn);
_logger.debug("EmailSettings successfully sent to [{}], Message:[{}]", emails, message);
}
代码示例来源:origin: jiang111/ReSend-SMS
HtmlEmail email = new HtmlEmail();
email.setHostName(hostName);
email.setSmtpPort(ssLPort);
email.setSSL(true);
email.setCharset("utf8");
email.addTo(sendTo);
email.setFrom(sendFrom);
email.setAuthentication(user, passwd);
email.setSubject(TextUtils.isEmpty(subject) ? "你有新短信了" : subject);
email.setMsg(TextUtils.isEmpty(body) ? "null" : body);
email.send();
mHandler.post(new Runnable() {
@Override
代码示例来源:origin: javahongxi/whatsmars
/**
* content为html,此方法将会对html进行转义。
* @param targetAddress
* @param title
* @param content
* @throws Exception
*/
public void sendHtmlEmail(String targetAddress,String title,String content) throws Exception {
HtmlEmail email = new HtmlEmail();
email.setSubject(title);
email.setHtmlMsg(content);
email.addTo(targetAddress);
sendEmail(email);
}
代码示例来源:origin: com.stormpath.sdk/stormpath-sdk-impl
} else if (HTML == mimeType) {
HtmlEmail htmlEmail = new HtmlEmail();
htmlEmail.setHtmlMsg(renderEmail(emailTemplate.getHtmlBody(), context).toString());
email = htmlEmail;
} else { // both
HtmlEmail htmlEmail = new HtmlEmail();
htmlEmail.setHtmlMsg(renderEmail(emailTemplate.getHtmlBody(), context).toString());
htmlEmail.setTextMsg(renderEmail(emailTemplate.getTextBody(), context).toString());
email = htmlEmail;
log.debug("Finish email send to: {}", request.getToAddress());
} catch (EmailException e) {
log.error("Failed to send email: {}", e.getMessage(), e);
内容来源于网络,如有侵权,请联系作者删除!