如何使用jsp发送附件电子邮件?

时间:2014-07-06 10:46:59

标签: jsp email-attachments

我需要使用jsp发送附件电子邮件并在代码下面使用,但由于无法发送消息而发生错误。使用相同的代码编译时没有发生错误。但在运行时,由于无法发送消息而发生错误。编码是:

<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%
   String result;
   String to = "abcd@gmail.com"; 
   String from = "mcmohd@gmail.com";   
   String host = "localhost";
   Properties properties = System.getProperties(); 
    properties.setProperty("mail.smtp.host", host);
     Session mailSession = Session.getDefaultInstance(properties);

   try{

      MimeMessage message = new MimeMessage(mailSession);   

      message.setFrom(new InternetAddress(from));   

      message.addRecipient(Message.RecipientType.TO,
                               new InternetAddress(to));   

      message.setSubject("This is the Subject Line!");   

      BodyPart messageBodyPart = new MimeBodyPart();    

      messageBodyPart.setText("This is message body");          

      Multipart multipart = new MimeMultipart();    

      multipart.addBodyPart(messageBodyPart);    

      messageBodyPart = new MimeBodyPart();
      String filename = "file.txt";
      DataSource source = new FileDataSource(filename);
      messageBodyPart.setDataHandler(new DataHandler(source));
      messageBodyPart.setFileName(filename);
      multipart.addBodyPart(messageBodyPart);


      message.setContent(multipart );


      Transport.send(message);
      String title = "Send Email";
      result = "Sent message successfully....";
   }catch (MessagingException mex) {
      mex.printStackTrace();
      result = "Error: unable to send message....";
   }
%>
<html>
<head>
<title>Send Attachement Email using JSP</title>
</head>
<body>
<center>
<h1>Send Attachement Email using JSP</h1>
</center>
<p align="center">
<% 
   out.println("Result: " + result + "\n");
%>
</p>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

根据错误,您在评论error occurred as configure the SMTP server中发布,我可以看到您的主机名无效。

试试这个,

   String host = "smtp.gmail.com";
   Properties properties = System.getProperties(); 
   properties.setProperty("mail.smtp.host", host);
   Session mailSession = Session.getDefaultInstance(properties);

注意: 我已将来自地址的smtp主机名用作gmail。 smtp服务器主机名更改与邮件服务器

希望这有帮助