1 18 package org.apache.axis2.transport.mail; 19 20 import org.apache.axis2.engine.AxisFault; 21 import org.apache.axis2.transport.EmailReceiver; 22 23 import javax.mail.*; 24 import javax.mail.internet.AddressException ; 25 import javax.mail.internet.InternetAddress ; 26 import javax.mail.internet.MimeMessage ; 27 import java.util.Properties ; 28 29 35 public class EMailSender { 36 private String user; 37 private String host; 38 private String smtpPort; 39 private String password; 40 41 public EMailSender(String user, String host, String smtpPort, String password) { 42 this.user = user; 43 this.host = host; 44 this.smtpPort = smtpPort; 45 this.password = password; 46 } 47 48 public void send(String subject, String targetEmail, String message) throws AxisFault { 49 try { 50 final PasswordAuthentication authentication = 51 new PasswordAuthentication(user, password); 52 Properties props = new Properties (); 53 props.put("mail.user", user); 54 props.put("mail.host", host); 55 props.put("mail.store.protocol", "pop3"); 56 props.put("mail.transport.protocol", "smtp"); 57 props.put("mail.smtp.port", smtpPort); 58 Session session = Session.getInstance(props, new Authenticator() { 59 protected PasswordAuthentication getPasswordAuthentication() { 60 return authentication; 61 } 62 }); 63 64 MimeMessage msg = new MimeMessage (session); 65 msg.setFrom(new InternetAddress ((user))); 66 msg.addRecipient(Message.RecipientType.TO, new InternetAddress (targetEmail)); 67 msg.setSubject(subject); 68 69 msg.addHeaderLine("Content-Type: text/plain; charset=us-ascii"); 70 71 msg.setText(message); 72 msg.setHeader("Content-Transfer-Encoding", "7bit"); 73 Transport.send(msg); 74 } catch (AddressException e) { 75 throw new AxisFault(e); 76 } catch (MessagingException e) { 77 throw new AxisFault(e); 78 } 79 } 80 81 public static void main(String [] args) throws Exception { 82 83 String user = "hemapani"; 84 String host = "127.0.0.1"; 85 String smtpPort = "25"; 86 String password = "hemapani"; 87 EMailSender sender = new EMailSender(user, host, smtpPort, password); 88 89 sender.send("Testing mail sending", "hemapani@127.0.0.1", "Hellp, testing"); 90 91 EmailReceiver receiver = new EmailReceiver(user, host, "110", password); 92 receiver.connect(); 93 Message [] msgs = receiver.receive(); 94 if (msgs != null) { 95 for (int i = 0; i < msgs.length; i++) { 96 MimeMessage msg = (MimeMessage ) msgs[i]; 97 if (msg != null) { 98 System.out.println(msg.getSender()); 99 System.out.println(msg.getContent()); 100 } 101 msg.setFlag(Flags.Flag.DELETED, true); 102 } 103 104 } 105 receiver.disconnect(); 106 107 } 108 } 109 | Popular Tags |