我创建了一种使用带有多文件附件的java GUI发送邮件的方法。当该方法发送邮件时,它将附件文件类型如microsoft office和pdf作为BitSarver发送到接收邮件。我需要提交文件以发送类型,以便其他自动系统可以通过阅读附件文件并打印它来工作。
这是方法。
static public boolean sendMail(String to,String subject,String text_filed)
{
Properties props = new Properties();
props.put("mail.smtp.host","smtp.gmail.com");
props.put("mail.smtp.socketFactory.port ","465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth","true");
props.put("mail.smtp.port","465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("eamil", pass);
}
}
);
try
{
Message m = new MimeMessage(session);
m.setFrom(new InternetAddress(userMAil));
System.out.println("from "+userMAil);
m.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
System.out.println("to "+to);
m.setSubject(subject);
System.out.println("the subject "+subject);
MimeBodyPart bodypart = new MimeBodyPart();
bodypart.setText(text_filed);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bodypart);
System.out.println("the content "+text_filed);
for(int i = 0;i< main_controller.attachments_path.size();i++)
{
bodypart = new MimeBodyPart();
DataSource source = new FileDataSource(main_controller.attachments_path.get(i));
System.out.println("the file location"+main_controller.attachments_path.get(i));
bodypart.setDataHandler(new DataHandler(source));
//bodypart.setFileName(main_controller.filesFrame.getFilename());
System.out.println("the file name"+main_controller.filesFrame.getFilename());
multipart.addBodyPart(bodypart);
}
m.setContent(multipart);
//m.setText(text_filed);
Transport.send(m);
JOptionPane.showMessageDialog(null, "done!");
return true;
}
catch(Exception e)
{
String m = e.getMessage();
JOptionPane.showMessageDialog(null, e);
System.out.println(m);
return false;
}
}
希望你能帮助我:D
答案 0 :(得分:0)
似乎问题可能与此有关:
How to set MimeBodyPart ContentType to "text/html"?
尝试在提交之前调用MimeMessage.saveChanges()以从DataHandler中正确填充内容类型。
答案 1 :(得分:0)
JavaMail通过JavaBeans Activation Framework(JAF)根据文件扩展名选择MIME类型。 “已知”文件扩展名列表相对较小。您可以按照MimetypesFileTypeMap javadocs中的说明添加它。或者,您可以使用MimeBodyPart.attachFile方法并直接指定MIME类型。
哦,你要清理这些common JavaMail mistakes。