簡體   English   中英

無法使用Javamail API發送帶有附件的郵件

[英]Unable to send mail with attached file using Javamail API

我正在嘗試發送包含這些代碼的電子郵件,但是出現錯誤。

import java.util.*;
import javax.mail.*;
import javax.activation.*;
import javax.mail.internet.*;

public class SendEmail {

  public static void main(String args[]) throws Exception {
  String host = "localhost";
  String from = "myemail@hotmail.com";
  String to = "recipientemail@hotmail.com";

  Properties properties = System.getProperties();

  properties.setProperty("mail.smtp.host", host);

  Session session = Session.getDefaultInstance(properties);

  Message message = new MimeMessage(session);
  message.setFrom(new InternetAddress(from));
  message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
  message.setSubject("JavaMail Attachment");

  BodyPart messageBodyPart = new MimeBodyPart();

  messageBodyPart.setText("hi");

  Multipart multipart = new MimeMultipart();
  multipart.addBodyPart(messageBodyPart);

  //attachment
  messageBodyPart = new MimeBodyPart();
  String filename = "C:/Users/ME/Desktop/file.txt";
  DataSource source = new FileDataSource(filename);
  messageBodyPart.setDataHandler(new DataHandler(source));
  messageBodyPart.setFileName(filename);
  multipart.addBodyPart(messageBodyPart);

  message.setContent(multipart);

  Transport.send(message);
  System.out.println("Msg Send ....");
  }
}

我收到“ HTTP狀態404”錯誤,描述為“請求的資源()不可用”。
我可以知道為什么以及如何解決嗎?
抱歉,我是編程和Java的初學者

提前致謝!

聽起來您正在嘗試在Web服務器中執行此操作。

您需要以某種方式告訴Web服務器如何調用您的代碼。 最簡單的方法是在JSP頁面內執行此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM