我在这里附上了我的示例来源。我在系统中有一个html模板和路径。我的目标是需要发送带有邮件的HTML模板。但我必须使用html路径附加HTML消息。怎么做。
public class SendMail {
public void sendingEmailToClient(String sEmail,String sUserName,String htmlPath) throws Exception{
String fromMerchant=null;
String merchantPassword=null;
String toClientMail=null;
String userName=null;
String smtp=null;
String smtpServer=null;
String smtpSocketFactory=null;
String smtpPort=null;
String socketFactoryClass=null;
String sslSocketFactory=null;
String smtpAuthentication=null;
String smtpAuthenticateState=null;
String mailSmtpPort=null;
if(sEmail!=null && !sEmail.isEmpty() && sUserName !=null && !sUserName.isEmpty()){
toClientMail=sEmail;
userName=sUserName;
System.out.println("The user name is ==>"+userName);
fromMerchant="vikki@gmail.com";
merchantPassword="passw0rd";
Properties properties=new Properties();
smtp="mail.smtp.host";
smtpServer="smtp.gmail.com";
smtpSocketFactory="mail.smtp.socketFactory.port";
smtpPort="465";
socketFactoryClass="mail.smtp.socketFactory.class";
sslSocketFactory="javax.net.ssl.SSLSocketFactory";
smtpAuthentication="mail.smtp.auth";
smtpAuthenticateState="true";
mailSmtpPort="mail.smtp.port";
properties.put(smtp,smtpServer);
properties.put(smtpSocketFactory, smtpPort);
properties.put(socketFactoryClass, sslSocketFactory);
properties.put(smtpAuthentication, smtpAuthenticateState);
properties.put(mailSmtpPort,smtpPort);
Session session=Session.getDefaultInstance(properties,new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication ("vikki@gmail.com","passw0rd");
}
});
try{
MimeMessage message=new MimeMessage(session);
message.setFrom(new InternetAddress("LoyaltyCart"));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(toClientMail));
message.setText(" Hi "+userName+"\n You have successfully registered on YourShopping !!.. \n We heartly welcomes you and save your money, buy new products...");
**//Need to append the HTML template using file path with message like message.setHTMLTemplate**
Transport.send(message);
System.out.println("message sent successfully");
message.setText("You have successfully registered on YourShopping !!..");
message.setText("We heartly welcomes you and save your money, buy new products...");
}catch(Exception e){
throw new RuntimeException(e);
}
}
}}
答案 0 :(得分:0)
如果您想使用HTML文件作为邮件内容,可以使用setDataHandler:
String htmlFileName = "/home/vikki/Documents/MailTemplate.html";
message.setDataHandler(
new DataHandler(new FileDataSource(htmlFileName)));
如果您想将HTML文件设为内联附件:
String htmlFileName = "/home/vikki/Documents/MailTemplate.html";
MimeBodyPart part = new MimeBodyPart();
part.attachFile(htmlFileName);
part.setDisposition(Part.INLINE);
message.setContent(new MimeMultipart(part));
这两种方法仅提供平坦的HTML内容。如果HTML包含图像,则需要使用外部URL(可能是Internet URL)链接到它们。大多数电子邮件客户端默认阻止指向外部图像的链接。您可以通过附加每个图像来修改HTML,并按照Content-Id中的说明修改HTML以指向每个图像的RFC 2392,但它会使信息本身变大。