2013-04-20 23 views
28

Sto tentando di inviare e-mail utilizzando java e g mail Ho archiviato i miei file sul cloud e i file memorizzati che desidero inviare come allegato alla mia posta.Invio di allegati di posta tramite Java

È necessario aggiungere i file a questa e-mail e non i collegamenti di tali file.

Come posso inviare tali allegati?

+0

Devi essere in grado di scaricare i file giù dalla nuvola nel codice. Dopo di che, basta collegare –

+0

Esempio http://www.tutorialspoint.com/javamail_api/javamail_api_send_email_with_attachment.htm –

+0

Utilizzare questa API: https://sourceforge.net/projects/easymail4j/ –

risposta

43

codice di lavoro, ho usato Java 1.4.7 posta vaso

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

public class MailProjectClass { 

public static void main(String[] args) { 

    final String username = "[email protected]"; 
    final String password = "your.password"; 

    Properties props = new Properties(); 
    props.put("mail.smtp.auth", true); 
    props.put("mail.smtp.starttls.enable", true); 
    props.put("mail.smtp.host", "smtp.gmail.com"); 
    props.put("mail.smtp.port", "587"); 

    Session session = Session.getInstance(props, 
      new javax.mail.Authenticator() { 
       protected PasswordAuthentication getPasswordAuthentication() { 
        return new PasswordAuthentication(username, password); 
       } 
      }); 

    try { 

     Message message = new MimeMessage(session); 
     message.setFrom(new InternetAddress("[email protected]")); 
     message.setRecipients(Message.RecipientType.TO, 
       InternetAddress.parse("[email protected]")); 
     message.setSubject("Testing Subject"); 
     message.setText("PFA"); 

     MimeBodyPart messageBodyPart = new MimeBodyPart(); 

     Multipart multipart = new MimeMultipart(); 

     messageBodyPart = new MimeBodyPart(); 
     String file = "path of file to be attached"; 
     String fileName = "attachmentName"; 
     DataSource source = new FileDataSource(file); 
     messageBodyPart.setDataHandler(new DataHandler(source)); 
     messageBodyPart.setFileName(fileName); 
     multipart.addBodyPart(messageBodyPart); 

     message.setContent(multipart); 

     System.out.println("Sending"); 

     Transport.send(message); 

     System.out.println("Done"); 

    } catch (MessagingException e) { 
     e.printStackTrace(); 
    } 
    } 
} 
+0

lievitare connessione un'eccezione di timeout –

+0

ho usato la tua classe, ma dà un errore come questo, "530 5.7.0 Deve prima emettere un comando STARTTLS. pa5sm839428pdb.28 - gsmtp" @NINCOMPOOP –

+0

Prova ad aggiungere questo: 'props.put (" mail.smtp.EnableSSL.enable " , "true"); ' – NINCOMPOOP

0

Utilizzando Spring Framework, è possibile aggiungere molti allegati:

package com.mkyong.common; 


import javax.mail.MessagingException; 
import javax.mail.internet.MimeMessage; 

import org.springframework.core.io.FileSystemResource; 
import org.springframework.mail.MailParseException; 
import org.springframework.mail.SimpleMailMessage; 
import org.springframework.mail.javamail.JavaMailSender; 
import org.springframework.mail.javamail.MimeMessageHelper; 

public class MailMail 
{ 
    private JavaMailSender mailSender; 
    private SimpleMailMessage simpleMailMessage; 

    public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) { 
     this.simpleMailMessage = simpleMailMessage; 
    } 

    public void setMailSender(JavaMailSender mailSender) { 
     this.mailSender = mailSender; 
    } 

    public void sendMail(String dear, String content) { 

     MimeMessage message = mailSender.createMimeMessage(); 

     try{ 
     MimeMessageHelper helper = new MimeMessageHelper(message, true); 

     helper.setFrom(simpleMailMessage.getFrom()); 
     helper.setTo(simpleMailMessage.getTo()); 
     helper.setSubject(simpleMailMessage.getSubject()); 
     helper.setText(String.format(
      simpleMailMessage.getText(), dear, content)); 

     FileSystemResource file = new FileSystemResource("/home/abdennour/Documents/cv.pdf"); 
     helper.addAttachment(file.getFilename(), file); 

     }catch (MessagingException e) { 
     throw new MailParseException(e); 
     } 
     mailSender.send(message); 
     } 
} 

Per sapere come configurare il vostro progetto per affrontare questo codice, completa la lettura this tutorial.

11

Per un u Perchè, la risposta accettata funziona parzialmente quando invio email al mio indirizzo Gmail. Ho l'allegato ma non il testo dell'email.

Se si desidera sia l'attaccamento e il testo provare questo in base alla risposta accettata:

Properties props = new java.util.Properties(); 
    props.put("mail.smtp.host", "yourHost"); 
    props.put("mail.smtp.port", "yourHostPort"); 
    props.put("mail.smtp.auth", "true");    
    props.put("mail.smtp.starttls.enable", "true"); 


    // Session session = Session.getDefaultInstance(props, null); 
    Session session = Session.getInstance(props, 
       new javax.mail.Authenticator() { 
       protected PasswordAuthentication getPasswordAuthentication() { 
        return new PasswordAuthentication("user", "password"); 
       } 
       }); 


    Message msg = new MimeMessage(session); 
    try { 
     msg.setFrom(new InternetAddress(mailFrom)); 
     msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo)); 
     msg.setSubject("your subject"); 

     Multipart multipart = new MimeMultipart(); 

     MimeBodyPart textBodyPart = new MimeBodyPart(); 
     textBodyPart.setText("your text"); 

     MimeBodyPart attachmentBodyPart= new MimeBodyPart(); 
     DataSource source = new FileDataSource(attachementPath); // ex : "C:\\test.pdf" 
     attachmentBodyPart.setDataHandler(new DataHandler(source)); 
     attachmentBodyPart.setFileName(fileName); // ex : "test.pdf" 

     multipart.addBodyPart(textBodyPart); // add the text part 
     multipart.addBodyPart(attachmentBodyPart); // add the attachement part 

     msg.setContent(multipart); 


     Transport.send(msg); 
    } catch (MessagingException e) { 
     LOGGER.log(Level.SEVERE,"Error while sending email",e); 
    } 
+1

Questa modifica ha funzionato per me. Stavo ricevendo l'allegato correttamente, ma non ottenendo alcun testo del corpo dell'e-mail. Con il codice esattamente come ha @amdev, ho ricevuto e-mail con il corpo del testo e l'allegato. Grazie! – snowmanjack

+0

d'accordo con sopra commento, questa dovrebbe essere la risposta accettata! – roz

Problemi correlati