2013-12-11 60 views
3

我有一个方法,我使用java发送电子邮件。我想知道如何将图片附加到电子邮件的顶部?我试过使用MimeMessageParts或什么,我不能得到它的工作?我想能够一个BufferedImage传递给方法的参数,它有它附着在上面..任何帮助将不胜感激:)将图片附加到使用java邮件发送的电子邮件API

public static void Send(final String username, final String password, 
    String recipientEmail, String ccEmail, String title, String message) 
    throws AddressException, MessagingException 
{ 

Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); 
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; 

// Get a Properties object 
Properties props = System.getProperties(); 
props.setProperty("mail.smtps.host", "smtp.gmail.com"); 
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); 
props.setProperty("mail.smtp.socketFactory.fallback", "false"); 
props.setProperty("mail.smtp.port", "465"); 
props.setProperty("mail.smtp.socketFactory.port", "465"); 
props.setProperty("mail.smtps.auth", "true"); 


props.put("mail.smtps.quitwait", "false"); 

Session session = Session.getInstance(props, null); 

// -- Create a new message -- 
final MimeMessage msg = new MimeMessage(session); 

// -- Set the FROM and TO fields -- 
msg.setFrom(new InternetAddress(username + "@gmail.com")); 
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false)); 

if (ccEmail.length() > 0) { 
    msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false)); 
} 

msg.setSubject(title); 
msg.setText(message, "utf-8"); 
msg.setSentDate(new Date()); 

SMTPTransport t = (SMTPTransport)session.getTransport("smtps"); 

t.connect("smtp.gmail.com", username, password); 
t.sendMessage(msg, msg.getAllRecipients());  
t.close(); 

} 

回答

1
  1. 对于附件,您需要创建单独的MimeBodyPart,下面是示例代码,

    MimeBodyPart attachmentPart = new MimeBodyPart(); 
    FileDataSource fileDataSource = new FileDataSource(filename) { 
        @Override 
    public String getContentType() { 
         return "application/octet-stream"; 
         } 
    }; 
    attachmentPart.setDataHandler(new DataHandler(fileDataSource)); 
    
  2. 对于邮件文本,你需要另一个MimeBodyPart

    MimeBodyPart messagePart = new MimeBodyPart(); 
    messagePart.setText(bodyText); 
    
  3. 结合这两种MimeBodyPartMultipart

    Multipart multipart = new MimeMultipart(); 
    multipart.addBodyPart(messagePart); 
    multipart.addBodyPart(attachmentPart); 
    
  4. 最后,发送电子邮件

    ........... 
    final MimeMessage msg = new MimeMessage(session); 
    msg.setContent(multipart); 
    Transport.send(msg); 
    

有关详细信息,请参阅本link

+0

你先生是惊人的:)感谢您的帮助和有用的链接! –

相关问题