IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

API standards et tierces Java Discussion :

probleme avec javax.mail et la classe MimeBodyPart


Sujet :

API standards et tierces Java

  1. #1
    Membre du Club
    Inscrit en
    Avril 2007
    Messages
    69
    Détails du profil
    Informations forums :
    Inscription : Avril 2007
    Messages : 69
    Points : 48
    Points
    48
    Par défaut probleme avec javax.mail et la classe MimeBodyPart
    voila je fais l envoie d un mail par l'api javax.mail

    code de la classe
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    package de.conti.ptc.tdm.utils.error;
     
    import java.awt.AWTException;
    import java.awt.Dimension;
    import java.awt.Rectangle;
    import java.awt.Robot;
    import java.awt.Toolkit;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.UnknownHostException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Properties;
    import java.util.StringTokenizer;
    import java.util.Vector;
     
    import javax.activation.DataHandler;
    import javax.activation.DataSource;
    import javax.activation.FileDataSource;
    import javax.imageio.ImageIO;
    import javax.mail.BodyPart;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Multipart;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.AddressException;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;
     
     
    public class IP3Exception extends IP3Logger{
     
    	private static IP3Exception instance    = null;
     
     
    	private InternetAddress[] getEmails() throws Exception{
     
    		String listEmails;
    		Vector<String> vectorEmails;
    		InternetAddress[] arrayEmails;
     
    		vectorEmails = new Vector<String>();
    		listEmails = getProperty("emails");
     
    		StringTokenizer tokenizer = new StringTokenizer(listEmails, ",");
     
    		while ( tokenizer.hasMoreTokens() ) {
    			vectorEmails.add(tokenizer.nextToken());
    		}
     
    		arrayEmails = new InternetAddress[vectorEmails.size()];
    		for (int i=0;i<vectorEmails.size();i++){
    			arrayEmails[i] = new InternetAddress(vectorEmails.get(i));
    		}
     
    		return arrayEmails;
    	}
     
    	public IP3Exception(Exception exception) {
    		String pattern;
    		InternetAddress[] internetAddresses;
    		String printScreenPath;
    		Session session;
    		Message message;
    		Multipart multipart;
    		DataSource source;
    		Properties prop;
     
    		try {		    
    			internetAddresses = getEmails();
     
    			//log informations
    			pattern = "User : " + System.getProperty("user.name") + "\n";
    			pattern += "PC : " + InetAddress.getLocalHost().getHostName() + "\n"; 
    			pattern += "Date : " + new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date()) +"\n"; 
    			pattern += "Milliseconds since the program start : " + (System.currentTimeMillis() - milliseconds_since_start) + "\n";            
    			pattern += "Message : " + exception.getLocalizedMessage() + "\n";
    			pattern += "Stacktrace : " + getStackTrace(exception) + "\n"; 
    			//Mail and server proprieties  with printscreen    
    			multipart = new MimeMultipart();           
    			prop = System.getProperties();
     
    			prop.put("mail.smtp.host", getProperty("smtp"));
    			session = Session.getDefaultInstance(prop,null);           
    			message = new MimeMessage(session);
    			message.setFrom(new InternetAddress(System.getProperty("user.name")));
    			message.setRecipients(Message.RecipientType.TO,internetAddresses);
    			message.setSubject("error ip3");
    			message.setHeader("X-Mailer", "Java");           
    			BodyPart messageBodyPart = new MimeBodyPart();            
    			messageBodyPart.setText(pattern);
    			multipart.addBodyPart(messageBodyPart);
    			//add printscreen
    			messageBodyPart = new MimeBodyPart();
    			printScreen();
     
    			printScreenPath = getProperty("printScreenFolder")
    								.replace("%uid", System.getProperty("user.name"))			
    								+"/IP3screenshot.png";
    			source = new FileDataSource(printScreenPath);
     
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(printScreenPath); 
                multipart.addBodyPart(messageBodyPart);
     
    			// add two parts of mail
                message.setContent(multipart);
     
    			//send logmail
    			Transport.send(message);
     
    			//errorlog file
    			sendErrorLogger(pattern);
    		} 
    		catch (Exception e) {		    
    			e.printStackTrace();
    		} 
     
     
    	}
     
     
    	public static IP3Exception getInstance(Exception exception){
    		if (instance == null) {
    			instance = new IP3Exception(exception);
    		}
    		return instance;
    	}
     
    	private String getStackTrace(Exception e) {
    		String stackTrace = "";
    		for (StackTraceElement stack : e.getStackTrace()) {
    			stackTrace += stack.getClassName() + "." + stack.getMethodName() + ":" + stack.getLineNumber() + "\n--> ";
    		}
    		return (stackTrace.substring(0, stackTrace.length() - 5) + "\n");
    	}
     
    	private void printScreen() throws AWTException, IOException {
     
    		String printScreenPath ;
     
    		Toolkit toolkit = Toolkit.getDefaultToolkit();
    		Dimension screenSize = toolkit.getScreenSize();
    		Rectangle screenRect = new Rectangle(screenSize);
    		// create screen shot
    		Robot robot = new Robot();
    		BufferedImage image = robot.createScreenCapture(screenRect);                      
    		// save captured image to PNG file
     
    		printScreenPath = getProperty("printScreenFolder")
    			.replace("%uid", System.getProperty("user.name"))			
    			+"/IP3screenshot.png";
    		ImageIO.write(image, "png", new File(printScreenPath));
    	}
     
    }
    si je lance cet envoi de mail par un classe de test ca marche nikel
    code classe de test
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    package de.conti.ptc.tdm.utils.error;
     
    public class TestLogger {
     
        /**
         * @param args
         */
        public static void main(String[] args) throws Exception {
            System.out.println("****************************jlhljhlm");
            IP3Logger.getInstance();
            Thread.sleep(1000);
            IP3Logger.getInstance().sendLogger();
            try {
     
                Integer.parseInt("Hello world");
                // } catch (NumberFormatException e) {
            } catch (Exception e) {
                IP3Exception.getInstance(e);
            }
     
            try {
                // plop();
            } catch (Exception e) {
                // IP3Exception.getInstance(e);
            }
     
        }
     
        public static void plop() throws Exception {
            throw new Exception("erreur levée dans plop!");
        }
     
    }
    Mais lorsque je lance cet envoie dans mon projet ca marche plus
    code projet
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    package de.conti.ptc.tdm.infopool3;
     
    import java.io.IOException;
     
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.graphics.Font;
    import org.eclipse.swt.layout.GridData;
    import org.eclipse.swt.layout.GridLayout;
    import org.eclipse.swt.widgets.Composite;
    import org.eclipse.swt.widgets.Display;
    import org.eclipse.swt.widgets.Label;
    import org.eclipse.swt.widgets.ProgressBar;
    import org.eclipse.ui.part.ViewPart;
     
    import de.conti.ptc.tdm.utils.NetworkTest.NetworkTestLogger;
     
    import de.conti.ptc.tdm.utils.calendarForIp3.ColorCache;
    import de.conti.ptc.tdm.utils.error.IP3Exception;
    import de.conti.ptc.tdm.utils.persistence.ToplinkSession;
    import de.conti.ptc.tdm.utils.plugin.OpenViewAction;
     
    /**
     * Empty view which allows to display something when no plugins are opened.
     */
    public class EmptyView extends ViewPart {
     
    	//ID of the view
    	public static final String ID = OpenViewAction.getEmptyViewId();	
     
    	//Text displayed inside the view
    	private static Label infoLabel;
    	private static Composite container;
    	private static ProgressBar progressBar;
    	private static boolean firstLoad = true;
    	private static float connectionTime;
     
     
    	/**
             * Defines the content of the view
             */
    	public void createPartControl(Composite parent) {
     
    		container = new Composite(parent, SWT.NONE);
     
    		container.setLayout(new GridLayout());
    		container.setBackground(ColorCache.getWhite());
     
     
    		if (firstLoad){
     
    			try {
    				Integer.parseInt("Hello world");
     
    			} catch (Exception e) {   
    				//marche pas !!!
    				IP3Exception.getInstance(e);
    			}
     
     
    			for (int i=0;i<20;i++){
    				new Label(container,SWT.NONE).setLayoutData(new GridData(SWT.CENTER, SWT.LEFT, true, false, 1, 1));;
    			}
     
    			infoLabel = new Label(container, SWT.NONE);
    			infoLabel.setFont(new Font(parent.getDisplay(),"Arial",10,SWT.BOLD));
    			infoLabel.setBackground(ColorCache.getWhite());
     
    			infoLabel.setText("Connecting to the Database...");
    			infoLabel.setLayoutData(new GridData(SWT.CENTER, SWT.LEFT, true, false, 1, 1));
     
    			progressBar = new ProgressBar(container,SWT.INDETERMINATE|SWT.BORDER);
    			progressBar.setLayoutData(new GridData(SWT.CENTER, SWT.LEFT, true, true, 1, 1));
     
    			progressBar.setMinimum(0);
    			progressBar.setMaximum(100);
    			progressBar.setSelection(30);
    			progressBar.setBounds(0,0,250,20);
     
    			firstLoad = false;
    		}
    	}
     
    	/**
             * Actions to do when the focus is on the view
             */
    	public void setFocus() {
    	}
     
     
    	public static void connection(){
     
     
    		final Thread threadEndConnection = new Thread() {
    			public void run() {
     
    			    try {
                        NetworkTestLogger.getInstance().sendLogger("IP3","TopLinkLoad");
                    } catch (IOException e) {
                    }
     
    				connectionTime = (float) ((System.currentTimeMillis() - ApplicationWorkbenchWindowAdvisor.startTime) / 1000.0);
     
    				progressBar.dispose();
     
    				infoLabel.setText("       Connected in " + connectionTime + " s");				               
    			}
    		};
     
    		Thread threadStartConnection = new Thread() {
    			public void run() {
     
    	            try {
                        NetworkTestLogger.getInstance();
                    } catch (IOException e1) {
                    }      
     
    			    ToplinkSession.getInstance();
    				try{
    					Display.getDefault().syncExec(threadEndConnection);
    				}
    				catch(Exception e){
    					//if the users opens a tab without waiting for the end of the connection
    					//do nothing
    				}
    			}
    		};
     
     
    		threadStartConnection.start();
    	}
    }
    et ca me fais comme erreur :
    Error creating the view.
    loader constraint violation: when resolving method "javax.mail.BodyPart.setDataHandler(Ljavax/activation/DataHandlerV" the class loader (instance of org/eclipse/osgi/internal/baseadaptor/DefaultClassLoader) of the current class, de/conti/ptc/tdm/utils/error/IP3Exception, and the class loader (instance of org/eclipse/osgi/internal/baseadaptor/DefaultClassLoader) for resolved class, javax/mail/BodyPart, have different Class objects for the type javax/activation/DataHandler used in the signature


    je comprends pas du tout le pourquoi du comment..

    pour info ca plante dans le constructeur de la classe IP3Exception a la ligne messageBodyPart.setDataHandler(new DataHandler(source));

    merci d avance pour votre aide

  2. #2
    Membre averti Avatar de Philcmoi
    Homme Profil pro
    Inscrit en
    Juillet 2006
    Messages
    666
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 53
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Juillet 2006
    Messages : 666
    Points : 412
    Points
    412
    Par défaut
    bonjour, dans webcontent de ton projet, as tu toujour quelque soit le nom de ta variable "printScreenPath" composée l'image .png ???? Et je vois que une resemblense de tes sources avec celle de sup info
    Utilises tu la bonne version java mail?

    voila dans l'espoir de t'aider.

    C'est bien ce que tu a fait, tu es tres fort mais tu utilises awt ou swing, mais par ta capture d'écran, est elle enregistrée dynamiquement dans ton projet ?
    c'est pour ca que je te parle de webcontent qui pourrait être tout simplement un espace ôu tu pourrais stocker dynamiquement tes captures d'écran !!!

    Es tu sure que ta méthode de capture écran fonctionne ???

  3. #3
    Membre du Club
    Inscrit en
    Avril 2007
    Messages
    69
    Détails du profil
    Informations forums :
    Inscription : Avril 2007
    Messages : 69
    Points : 48
    Points
    48
    Par défaut
    Pourrais tu expliquer plus précisement un maniere de stocker dynamiquement mon image .??
    effectivement je la stock en dur sur mon pc et je vais chercher ce fichier pour le mettre en piece jointe du mail..

    si tu as d autres piste.. je t en prie

  4. #4
    Membre averti Avatar de Philcmoi
    Homme Profil pro
    Inscrit en
    Juillet 2006
    Messages
    666
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 53
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Juillet 2006
    Messages : 666
    Points : 412
    Points
    412
    Par défaut
    En fait il faudrait que tu stocks ta capture d'écran et que la renomme "qqchose.png".

    Properties sys = System.getProperties();
    String os = sys.getProperty("os.name");
    Runtime r = Runtime.getRuntime();

    Voilà je mes connaissance s'arrêtent là.
    Je crois que ca t'aidera.
    allez moins de peine

  5. #5
    Membre du Club
    Inscrit en
    Avril 2007
    Messages
    69
    Détails du profil
    Informations forums :
    Inscription : Avril 2007
    Messages : 69
    Points : 48
    Points
    48
    Par défaut
    mon erreur vient du set datahandler et pas de la maniere de comment capturer l'image....

    c est cette commande la qui me plante a la gueule

    messageBodyPart.setDataHandler(new DataHandler(source));

    si quelqu une a une idée???

    est ce que ca vient de mon appli deveulloppée sous eclipse en projet divisé en plugins avec la techno RCP?????

    please help me i m very speed!!!!

  6. #6
    Membre averti Avatar de Philcmoi
    Homme Profil pro
    Inscrit en
    Juillet 2006
    Messages
    666
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 53
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Juillet 2006
    Messages : 666
    Points : 412
    Points
    412
    Par défaut
    le datahandler est bon mais c'est qu'il ne récupère pas le fichiers .png que tu as crée, utilise le system avec du code ms dos
    bon courrage

  7. #7
    Membre du Club
    Inscrit en
    Avril 2007
    Messages
    69
    Détails du profil
    Informations forums :
    Inscription : Avril 2007
    Messages : 69
    Points : 48
    Points
    48
    Par défaut
    pourtant j ai la bonne adresse pour mon fichier apres verif.....

    et puis ce que je ne comprend pas c est que ca marche pour la classe de test mais pas pour mon projet

  8. #8
    Membre averti Avatar de Philcmoi
    Homme Profil pro
    Inscrit en
    Juillet 2006
    Messages
    666
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 53
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Juillet 2006
    Messages : 666
    Points : 412
    Points
    412
    Par défaut
    alors fait comme ton test apres création de tes fichiers ;png
    c'est ton prope code, tu as trouver la solution elle est devant tes yeux c'est toi qui l'as fait.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
            IP3Logger.getInstance();
     
            IP3Logger.getInstance().sendLogger();

  9. #9
    Membre du Club
    Inscrit en
    Avril 2007
    Messages
    69
    Détails du profil
    Informations forums :
    Inscription : Avril 2007
    Messages : 69
    Points : 48
    Points
    48
    Par défaut
    bon bon!!!
    apres moultes petages de cables, et mure reflexion sur cette connerie de ******, je pense que l erreur ne vient pas du code directement mais de la structure en pluggin et / ou la techno RCP!!!!!

    je vous renvoi donc sur un sujet dédié a ca!!
    http://www.developpez.net/forums/sho...75#post3511075

    et si vous avez des idées bienvenue !!!
    sinon je vais suicider mon pc et la machine a café!!

Discussions similaires

  1. probleme avec javax.servlet.jsp.tagext.Tag
    Par faico dans le forum JSF
    Réponses: 2
    Dernier message: 30/03/2007, 11h38
  2. [SQL] probleme avec script mail menu deroulant
    Par gtraxx dans le forum PHP & Base de données
    Réponses: 2
    Dernier message: 22/09/2006, 03h04
  3. probleme avec la creation d une classe "polynome"
    Par le_voisin dans le forum C++
    Réponses: 10
    Dernier message: 05/09/2006, 00h52
  4. [Mail] probleme avec fonction mail() !!!
    Par H-bil dans le forum Langage
    Réponses: 6
    Dernier message: 19/06/2006, 23h45
  5. probleme package javax.mail
    Par gianni17 dans le forum Langage
    Réponses: 5
    Dernier message: 30/05/2006, 13h50

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo