Envoie Mail avec Java ?

Soadnemesis Messages postés 4 Date d'inscription lundi 15 mars 2010 Statut Membre Dernière intervention 27 décembre 2013 - 30 avril 2010 à 09:02
Soadnemesis Messages postés 4 Date d'inscription lundi 15 mars 2010 Statut Membre Dernière intervention 27 décembre 2013 - 30 avril 2010 à 09:10
Bonjour à tous,

Je cherche actuellement une Classe me permettant d'envoyer des mails avec Java. J'ai trouvé ce tutoriel que j'ai suivis à la lettre.

http://wiki.netbeans.org/SendMailUsingJavaFromNetBeans

Les seules différences sont que j'utilise Netbean 6.8 et Tomcat à la place de Glassfish.
De plus j'ai fais 2 modifications dans les lignes suivantes


private class SMTPAuthenticator extends javax.mail.Authenticator {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username =  "mon_adresse_gmail@gmail.com";           // specify your email id here (sender's email id)
            String password = "mon_password_gmail";                                  // specify your password here
            return new PasswordAuthentication(username, password);
        }
  }



Je n'ai aucunes erreurs et j'ai bien ajouté les librairies javamail-1.4.3 et jaf-1.1.1

Mon problème est que je n'arrive pas à envoyer d'email sur ma boite gmail ou n'importe quel autre boite mail d'ailleurs. J'obtiens toujours le message d'erreur "Mail NOT Sent to mon_adresse_gmail". Une idée ??

Je vous remercie d'avance pour votre aide.

1 réponse

Soadnemesis Messages postés 4 Date d'inscription lundi 15 mars 2010 Statut Membre Dernière intervention 27 décembre 2013
Modifié par pijaku le 27/12/2013 à 15:51
Je me dis que pour vous éviter de trop chercher le code sur le tuto il est peut être mieux que je le poste ici. Il y a 3 fichiers, 2 JSP pour l'interface et une Classe Mail.java.

Classe Mail.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jMail;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

/**
 *
 * @author Agraj
 */
public class Mail {
    
private String to;
private String from;
private String message;
private String subject;
private String smtpServ;

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getSmtpServ() {
        return smtpServ;
    }

    public void setSmtpServ(String smtpServ) {
        this.smtpServ = smtpServ;
    }

    public int sendMail(){
        try
        {
            Properties props = System.getProperties();
              // -- Attaching to default Session, or we could start a new one --
              props.put("mail.transport.protocol", "smtp");
              props.put("mail.smtp.starttls.enable","true");
              props.put("mail.smtp.host",smtpServ);
              props.put("mail.smtp.auth", "true");
              Authenticator auth = new SMTPAuthenticator();
              Session session = Session.getInstance(props, auth);
              // -- Create a new message --
              Message msg = new MimeMessage(session);
              // -- Set the FROM and TO fields --
              msg.setFrom(new InternetAddress(from));
              msg.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(to, false));
              // -- We could include CC recipients too --
              // if (cc != null)
              // msg.setRecipients(Message.RecipientType.CC
              // ,InternetAddress.parse(cc, false));
              // -- Set the subject and body text --
              msg.setSubject(subject);
              msg.setText(message);
              // -- Set some other header information --
              msg.setHeader("MyMail", "Java Mail Test");
              msg.setSentDate(new Date());
              // -- Send the message --
              Transport.send(msg);
              System.out.println("Message sent to"+to+" OK.");
              return 0;
        }
        catch (Exception ex)
        {
          ex.printStackTrace();
          System.out.println("Exception "+ex);
          return -1;
        }
  }
    
      private class SMTPAuthenticator extends javax.mail.Authenticator {
      
        
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username = "prenom.nom@gmail.com";
            String password = "soadnemesis";
            return new PasswordAuthentication(username, password);
        }
  }
}



index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"[http://www.w3.org/TR/html4/loose.dtd]">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title> Java Mail </title>
    </head>
    
        
        
        <form action="sendMail.jsp" method="POST">
            Send Mail ,

----

To,  :,
,

----

Subject,  :,
,

----

Message,  :,
<textarea name="message" rows="8" cols="30">
</textarea>,

----


            
        </form>
        
    
</html>





sendMail.jsp

<%-- 
    Document   : sendMail
    Created on : 29 Apr, 2008, 5:53:41 PM
    Author     : Agraj
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="mail" scope="session" class="jMail.Mail" />
<jsp:setProperty name="mail" property="to" param="to" />
<jsp:setProperty name="mail" property="from" value="Java.Mail.CA@gmail.com" />
<jsp:setProperty name="mail" property="smtpServ" value="smtp.gmail.com" />
<jsp:setProperty name="mail" property="subject" param="subject" />
<jsp:setProperty name="mail" property="message" param="message" />


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "[http://www.w3.org/TR/html4/loose.dtd]">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title> Send Mail </title>
    </head>
    
        
<%
String to = mail.getTo();
int result;

result = mail.sendMail();

if(result == 0){
    out.println(" Mail Successfully Sent to "+to);
}
else{
    out.println(" Mail NOT Sent to "+to);
}
    
%>
        
        
    
</html>
0
Rejoignez-nous