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
   | package test;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
 
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.event.*;
import javax.mail.internet.*;
 
public final class MailerBean  extends Object implements Serializable {
 
	/* Bean Properties */
        String  d_email = "monemail@gmail.com",
            d_password = "monpassword",
            d_host = "smtp.gmail.com",
            d_port  = "465",
            m_to = "desitinataire@gmail.com";
 
	private String subject;
        	private String message;
 
 
 
 
	public MailerBean() {
                    Properties props = new Properties();
                    props.put("mail.smtp.user", d_email);
        props.put("mail.smtp.host", d_host);
        props.put("mail.smtp.port", d_port);
        props.put("mail.smtp.starttls.enable","true");
        props.put("mail.smtp.auth", "true");
        //props.put("mail.smtp.debug", "true");
        props.put("mail.smtp.socketFactory.port", d_port);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
 
        SecurityManager security = System.getSecurityManager();;
	}
	/* Setter Methods */
 
public void setSubject(String subject) {
		this.subject = subject;
	}
 
	public void setMessage(String message) {
		this.message = message;
	}
 
	/* Sends Email */
	public void sendMail() throws Exception {
 
 
		try {
                    		   Properties props = (Properties)System.getProperties().clone();
                     Authenticator auth = new SMTPAuthenticator();
                                 Session session = Session.getInstance(props, auth);
 
 
 
            MimeMessage msg = new MimeMessage(session);
            msg.setText(this.message);
            msg.setSubject(this.subject);
 
            msg.setFrom(new InternetAddress(d_email));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
            Transport.send(msg);
        }
        catch (Exception mex)
        {
            mex.printStackTrace();
        } 
    }
 
 
          public static void main(String[] args)
    {
        MailerBean blah = new MailerBean();
    }
 
    private class SMTPAuthenticator extends javax.mail.Authenticator
    {
 
        public PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(d_email, d_password);
        }
    }
} | 
Partager