2010-11-29 226 views
1

我有类似如下的...电子邮件附件?

public boolean sendmail (String host, String to, String from, 
String message, String subject, String cc){ 
     try 
     { 
     //Created TCP Connection to server 
     Socket s = new Socket(host, 25); 
     //Open our streams. 
     InputStream inStream = s.getInputStream(); 
     OutputStream outStream = s.getOutputStream(); 
     in = new Scanner(inStream); 
     out = new PrintWriter(outStream, true); 
     //get my info! 
     String hostName = InetAddress.getLocalHost().getHostName(); 
     //e-mail time! 

     receive(); 
     send("HELO" + host); 
     receive(); 
     send("MAIL FROM: <" + from + "\n"); 
     receive(); 
     send("RCPT TO: <" + to + "\n"); 
     receive(); 
     send("DATA"); 
     receive(); 
     send("DATA"); 
     receive(); 
     //Make sure to close the everything again!! 
     out.close(); 
     in.close(); 
     s.close(); 
     return true; 
     } 
     catch (Exception e) 
     { 
      appendtolog("ERROR: " + e); 
      return false; 
     } 
    } 

private void send(String s) throws IOException{ 
    appendtolog(s); 
    out.print(s.replaceAll("\n", "\r\n")); 
    out.print("\r\n"); 
    out.flush(); 
} 

private void receive(){ 
    String line = in.nextLine(); 
    appendtolog(line); 
} 

是有可能只是把附件的地方在那里?我知道有这样使用API​​的方式,但我不知道有什么方法可以让我锤附件功能合并到或使用类似..

// Set the email attachment file 
MimeBodyPart attachmentPart = new MimeBodyPart(); 
FileDataSource fileDataSource = new FileDataSource(filename) { 
@Override 
public String getContentType() { 
    return "application/octet-stream"; 
} 
}; 
attachmentPart.setDataHandler(new DataHandler(fileDataSource)); 
    attachmentPart.setFileName(filename); 
+2

为什么不使用Java Mail API? – 2010-11-29 13:26:47

+2

*“我意识到有更多使用API​​的方法,但我想知道有什么方法可以打印附件的功能......”*是的,当然可以。您也可以编写自己的操作系统。问题必须是**为什么**?! Java Mail API的使用非常简单,经过充分测试和记录良好......如果您正在做某些事情来学习SMTP的来龙去脉,但是如果您尝试使用“MimeBodyPart”这样,显然不是... – 2010-11-29 13:32:47

回答

2

我建议回到基础并阅读关于此的RFC。

Internet邮件格式 http://www.faqs.org/rfcs/rfc2822.html

多用途Internet邮件扩展(MIME)第一部分:互联网消息体的格式 http://www.faqs.org/rfcs/rfc2045.html

这些都或多或少地直线前进,有一些神秘的东西在里面,但你应该能够明白你需要什么。

我会建议试着尽可能地分开沟通(你已经得到了上面的内容)和身体(消息内容),否则你会浑浊水域。

希望有所帮助。

1

这显然是可能的,但我d建议你使用JavaMail API而不是处理SMTP协议的血腥细节。除非您正在实施学生练习,否则这是正确的。