我想阅读HTML文件,并希望发送HTML格式的电子邮件。
public class SendEmailer {
public void sendHtmlEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) throws AddressException,
MessagingException {
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// sets SMTP server properties
Properties properties = new Properties();
properties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
properties.setProperty("mail.smtp.socketFactory.fallback", "false");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.store.protocol","pop3");
properties.put("mail.transport.protocol","smtp");
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
// set plain text message
msg.setContent(message, "text/html");
// sends the e-mail
Transport.send(msg);
}
//Code to read HTML document.
public void readHTML(String strfilename,String content){
// content="";
String str="";
try{
FileReader fr=new FileReader(strfilename);
BufferedReader br=new BufferedReader(fr);
while((str=br.readLine())!=null){
System.out.println(str.toString());
content+=str;
}
br.close();
}catch(IOException ie){
ie.printStackTrace();
}
}
public static void main(String[] args) {
// SMTP server information
String host = "myhost.com";
String port = "465";
String mailFrom = "abc@myhost.com";
String password = "abcd123";
// outgoing message information
String mailTo = "abc@gmail.com";
String subject = "Test mail";
// message contains HTML markups
String message = "<i>Greetings!Sending HTML mail.</i><br>";
message += "<font color=red>MyName</font>";
SendEmailer mailer = new SendEmailer ();
String filename="E:/filepath/filename.html";
try {
mailer.readHTML(filename);
mailer.sendHtmlEmail(host, port, mailFrom, password, mailTo,
subject, message);
System.out.println("Email sent successfully.");
} catch (Exception ex) {
System.out.println("Failed to sent email.");
ex.printStackTrace();
}
}
}
我可以成功发送电子邮件。但现在我想发送html文件的完整正文部分。我写了一个方法readHTML()
,但它没有读取该文件的内容,也没有发送相同的内容。它只发送我在消息变量中存储的内容。我在哪里弄错了?