2013-06-17 20 views
6

Sto tentando di inviare un'e-mail con un file allegato in Java.Invio di un'e-mail con un allegato utilizzando l'API javamail

Quando invio l'e-mail senza un allegato, ricevo l'e-mail, ma quando aggiungo l'allegato non ricevo nulla e non ricevo alcun messaggio di errore.

Questo è il codice che sto usando:

public void send() throws AddressException, MessagingException{ 
    //system properties 

Properties props = new Properties(); 
props.put("mail.smtp.localhost", "localhost"); 
props.put("mail.smtp.host",Configurations.getInstance().email_serverIp); 


/* 
* create some properties and get the default Session 
*/ 
session = Session.getDefaultInstance(props, null); 

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

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(); 
    generateCsvFile("/tmp/test.csv"); 
messageBodyPart = new MimeBodyPart(); 
String file = "/tmp/test.csv"; 
String fileName = "test.csv"; 
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"); 

} 

private static void generateCsvFile(String sFileName) 
{ 
    try 
    { 

    FileWriter writer = new FileWriter(sFileName); 

    writer.append("DisplayName"); 
    writer.append(','); 
    writer.append("Age"); 
    writer.append(','); 
    writer.append("YOUR NAME"); 
    writer.append(','); 

    writer.append('\n'); 
    writer.append("Zou"); 
    writer.append(','); 
    writer.append("26"); 
    writer.append(','); 
    writer.append("zouhaier"); 


    //generate whatever data you want 

    writer.flush(); 
    writer.close(); 
    } 
    catch(IOException e) 
    { 
     e.printStackTrace(); 
    } 
} 

Come posso correggere questo?

risposta

12
  1. Disabilitare vostro Anti Virus

perché avete qualche avvertimento come questo

warning message form antivirus

Prova questo codice ... lo aiuterà a ....

public class SendMail { 
    public SendMail() throws MessagingException { 
     String host = "smtp.gmail.com"; 
     String Password = "............"; 
     String from = "[email protected]"; 
     String toAddress = "[email protected]"; 
     String filename = "C:/SendAttachment.java"; 
     // Get system properties 
     Properties props = System.getProperties(); 
     props.put("mail.smtp.host", host); 
     props.put("mail.smtps.auth", "true"); 
     props.put("mail.smtp.starttls.enable", "true"); 
     Session session = Session.getInstance(props, null); 

     MimeMessage message = new MimeMessage(session); 

     message.setFrom(new InternetAddress(from)); 

     message.setRecipients(Message.RecipientType.TO, toAddress); 

     message.setSubject("JavaMail Attachment"); 

     BodyPart messageBodyPart = new MimeBodyPart(); 

     messageBodyPart.setText("Here's the file"); 

     Multipart multipart = new MimeMultipart(); 

     multipart.addBodyPart(messageBodyPart); 

     messageBodyPart = new MimeBodyPart(); 

     DataSource source = new FileDataSource(filename); 

     messageBodyPart.setDataHandler(new DataHandler(source)); 

     messageBodyPart.setFileName(filename); 

     multipart.addBodyPart(messageBodyPart); 

     message.setContent(multipart); 

     try { 
      Transport tr = session.getTransport("smtps"); 
      tr.connect(host, from, Password); 
      tr.sendMessage(message, message.getAllRecipients()); 
      System.out.println("Mail Sent Successfully"); 
      tr.close(); 

     } catch (SendFailedException sfe) { 

      System.out.println(sfe); 
     } 
    } 
    public static void main(String args[]){ 
     try { 
      SendMail sm = new SendMail(); 
     } catch (MessagingException ex) { 
      Logger.getLogger(SendMail.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 
} 
1

Vedere le domande JavaMail per debugging tips. In particolare, la traccia del protocollo ti dirà di più su cosa sta succedendo in ciascun caso. Mentre sei lì, troverai suggerimenti per l'utilizzo di GMail.

Se l'unica differenza è in realtà solo l'aggiunta di un allegato, sembra improbabile che si tratti di un problema di autenticazione. Potresti ricevere un'eccezione che non stai notando poiché il tuo metodo di invio è dichiarato per il lancio di MessagingException.

1

È possibile accedere a Gmail utilizzando il nome utente e la password. Ma l'accesso verrà negato dall'account Gmail.

Quindi, è necessario modificare il livello di sicurezza andando alle impostazioni dell'account, sezione password e disdale le impostazioni di sicurezza del codice di verifica o abbassare il livello di sicurezza dipende dalla vecchia o ultima applicazione gmail.

Se si desidera inviare l'allegato tramite gmail accedendo alla directory locale, è necessario utilizzare l'oggetto File da impostare sulla classe di costruttore DataSource come indicato nel programma seguente. Ciò eviterà l'eccezione "Accesso negato".

import java.io.File;  
import java.io.IOException;  
import java.util.Properties; 
import javax.activation.DataHandler; 
import javax.activation.DataSource; 
import javax.activation.FileDataSource; 
import javax.mail.Message; 
import javax.mail.MessagingException; 
import javax.mail.Multipart; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeBodyPart; 
import javax.mail.internet.MimeMessage; 
import javax.mail.internet.MimeMultipart; 

public class EmailApp { 
    public static void main(String[] args)throws IOException { 
     final String username = "[email protected]"; 
     final String password = "mypassword"; 

     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("Dear Mail Crawler," + "\n\n No spam to my email, please!"); 
      message.setSubject("Testing Subject"); 
      message.setText("PFA"); 

      MimeBodyPart messageBodyPart = new MimeBodyPart(); 
      Multipart multipart = new MimeMultipart(); 
      messageBodyPart = new MimeBodyPart(); 

      String attachmentPath = "C:/TLS/logs/26-Mar-2015"; 
      String attachmentName = "LogResults.txt"; 

      File att = new File(new File(attachmentPath), attachmentName); 
      messageBodyPart.attachFile(att); 

      DataSource source = new FileDataSource(att); 
      messageBodyPart.setDataHandler(new DataHandler(source)); 
      messageBodyPart.setFileName(attachmentName); 
      multipart.addBodyPart(messageBodyPart); 
      message.setContent(multipart); 

      System.out.println("Sending"); 
      Transport.send(message); 
      Transport.send(message); 
      System.out.println("Done"); 
     } catch (MessagingException e) { 
      throw new RuntimeException(e); 
     } 
    } 
} 
Problemi correlati