001: package dinamica;
002:
003: import java.util.Properties;
004: import javax.mail.*;
005: import javax.mail.internet.*;
006:
007: /**
008: * Utility class to send mail using SMTP (JavaMail).<br>
009: * Provides very simple methods for sending text based emails.
010: *
011: * <br>
012: * Creation date: jan/14/2004<br>
013: * Last Update: Oct/10/2004<br>
014: * (c) 2004 Martin Cordova<br>
015: * This code is released under the LGPL license<br>
016: * @author Martin Cordova
017: * */
018: public class SimpleMail {
019:
020: /**
021: * Send a simple text message using a background thread
022: * @param host Mail server address
023: * @param from valid email address
024: * @param fromName Descriptive from name
025: * @param to valid email address
026: * @param subject Email subject
027: * @param body Message body (text only)
028: */
029: public void send(String host, String from, String fromName,
030: String to, String subject, String body) {
031: Thread t = new Thread(new BackgroundSender(host, from,
032: fromName, to, subject, body));
033: t.start();
034: }
035:
036: /**
037: * BackgroundSender<br>
038: * Send email using a separate Thread to avoid blocking
039: * Creation date: 29/07/2004<br>
040: * (c) 2004 Martin Cordova y Asociados<br>
041: * http://www.martincordova.com<br>
042: * @author Martin Cordova dinamica@martincordova.com
043: */
044: class BackgroundSender implements Runnable {
045:
046: String host = null;
047: String from = null;
048: String fromName = null;
049: String to = null;
050: String subject = null;
051: String body = null;
052:
053: public BackgroundSender(String host, String from,
054: String fromName, String to, String subject, String body) {
055: this .host = host;
056: this .from = from;
057: this .fromName = fromName;
058: this .to = to;
059: this .subject = subject;
060: this .body = body;
061: }
062:
063: public void run() {
064:
065: try {
066: //init email system
067: Properties props = System.getProperties();
068: props.put("mail.smtp.host", host);
069: Session session = Session.getDefaultInstance(props,
070: null);
071: session.setDebug(false);
072:
073: //recipients
074: InternetAddress[] toAddrs = null;
075: toAddrs = InternetAddress.parse(to, false);
076:
077: //create message
078: Message msg = new MimeMessage(session);
079: msg.setRecipients(Message.RecipientType.TO, toAddrs);
080: msg.setSubject(subject);
081: msg.setFrom(new InternetAddress(from, fromName));
082: msg.setText(body);
083:
084: //send
085: Transport.send(msg);
086: } catch (Throwable e) {
087: try {
088: String d = StringUtil
089: .formatDate(new java.util.Date(),
090: "yyyy-MM-dd HH:mm:ss");
091: System.err
092: .println("ERROR [dinamica.SimpleMail.BackgroundSender.run@"
093: + d + "]: " + e.getMessage());
094: } catch (Throwable e1) {
095: }
096: }
097:
098: }
099:
100: }
101:
102: }
|