如何使用 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;

   // Recipient's email ID needs to be mentioned.
   String to = "[email protected]";

   // Sender's email ID needs to be mentioned
   String from = "[email protected]";

   // Assuming you are sending email from localhost
   String host = "localhost";

   // Get system properties object
   Properties properties = System.getProperties();

   // Setup mail server
   properties.setProperty("mail.smtp.host", host);

   // Get the default Session object.
   Session mailSession = Session.getDefaultInstance(properties);

   try {
      // Create a default MimeMessage object.
      MimeMessage message = new MimeMessage(mailSession);

      // Set From: header field of the header.
      message.setFrom(new InternetAddress(from));

      // Set To: header field of the header.
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

      // Set Subject: header field
      message.setSubject("This is the Subject Line!");

      // Create the message part
      BodyPart messageBodyPart = new MimeBodyPart();

      // Fill the message
      messageBodyPart.setText("This is message body");

      // Create a multipart message
      Multipart multipart = new MimeMultipart();

      // Set text message part
      multipart.addBodyPart(messageBodyPart);

      // Part two is attachment
      messageBodyPart = new MimeBodyPart();

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

      // Send the complete message parts
      message.setContent(multipart );

      // Send message
      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 Attachment Email using JSP</title>
   </head>
   <body>
      <center>
         <h1>Send Attachment Email using JSP</h1>
      </center>
      <p align = "center">
         <%out.println("Result: " + result + "
");%> </p> </body> </html>

现在,让我们运行上述 JSP,以将文件作为附件发送,同时在给定的电子邮件 ID 上发送消息。

用户认证部分

如果出于认证目的,需要向电子邮件服务器提供用户 ID 和密码,则你可以按以下方式设置这些属性 −

输出

props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");

更新于: 2019 年 7 月 30 日

371 次浏览

开启你的 事业

完成课程并获得认证

开始学习
广告