The JavaMail API is not part of core Java SE, but an optional extension. In addition, it is required in Java Enterprise Edition. The JavaMail packages can be accessed in two ways :
- by placing j2ee.jar in the classpath
- or, by placing both mail.jar and activation.jar in the classpath
*********Sample code***************
import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
/**
* Handles sending email and attachments.
*/
public final class Emailer {
/** */
private String server = null;
/** */
private String smtpAuthUser="";
/** */
private String smtpAuthPassword="";
/**
* Method EmailHelper.
*
* @param server
*/
public Emailer(String server) {
super();
this.server = server;
}
/**
* @param server
* @param smtpAuthUser
* @param smtpAuthPassword
*/
public Emailer(String server,String smtpAuthUser,String smtpAuthPassword) {
super();
this.server = server;
this.smtpAuthUser=smtpAuthUser;
this.smtpAuthPassword=smtpAuthPassword;
}
/**
* Sends an email with the supplied content/attachments to the supplied
* recipients. Set attachments as null if there are no attachments
*
* @param tos
* java.lang.String the email addresses to send to, each
* separated by a comma
* @param from
* java.lang.String the email address sent from
* @param ccs
* java.lang.String the email addresses of ccs, each separated by
* a comma
* @param bcs
* java.lang.String the email addresses of bcs, each separated by
* a comma
* @param subject
* java.lang.String the subject of the email to send
* @param content
* java.lang.String the content of the email to send
* @param attachments
* com.wiree.rapide.dto.AttachmentList the attachments to be
* sent.
* @exception javax.mail.MessagingException
* if any of the email addresses are of an illegal format, or
* if there is an error with reading attachment files, or if
* the message can not be sent
*/
public final void send(String tos, String from, String ccs, String bcs, String subject, String content) throws javax.mail.MessagingException {
// Set properties for the session
Properties properties = new Properties();
properties.put("mail.smtp.host", server);
// Get default session instance with system properties
Session session = Session.getDefaultInstance(properties);
// Create Message instance for the Session
Message msg = new MimeMessage(session);
// create recipient object
InternetAddress addressRecipients = new InternetAddress();
// create from object
InternetAddress addressFrom = new InternetAddress(from);
// Set Message content and properties
msg.setRecipients(Message.RecipientType.TO, addressRecipients.parse(tos));
msg.setRecipients(Message.RecipientType.CC, addressRecipients.parse(ccs));
msg.setRecipients(Message.RecipientType.BCC, addressRecipients.parse(bcs));
msg.setFrom(addressFrom);
msg.setSubject(subject);
msg.setContent(content, "text/plain");
// Send Message
Transport.send(msg);
}
/**
* Sends an authenticated email with the supplied content/attachments to the supplied
* recipients. Set attachments as null if there are no attachments
*
* @param tos
* java.lang.String the email addresses to send to, each
* separated by a comma
* @param from
* java.lang.String the email address sent from
* @param ccs
* java.lang.String the email addresses of ccs, each separated by
* a comma
* @param bcs
* java.lang.String the email addresses of bcs, each separated by
* a comma
* @param subject
* java.lang.String the subject of the email to send
* @param content
* java.lang.String the content of the email to send
* @param attachments
* com.wiree.rapide.dto.AttachmentList the attachments to be
* sent.
* @exception javax.mail.MessagingException
* if any of the email addresses are of an illegal format, or
* if there is an error with reading attachment files, or if
* the message can not be sent
* @throws IllegalArgumentException smtpAuthUser, smtpAuthPassword is not set
*/
public final void sendAuthenticated(String tos, String from, String ccs, String bcs, String subject, String content) throws javax.mail.MessagingException {
if (smtpAuthUser == null || smtpAuthUser.equals(""))
throw new IllegalArgumentException("smtpAuthUser has not been found");
if (smtpAuthPassword == null || smtpAuthPassword.equals(""))
throw new IllegalArgumentException("smtpAuthPassword has not been found");
// Set properties for the session
Properties properties = new Properties();
properties.put("mail.smtp.host", server);
properties.put("mail.transport.protocol", "smtp");
properties.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
// Get default session instance with system properties
Session session = Session.getDefaultInstance(properties, null);
// Create Message instance for the Session
Message msg = new MimeMessage(session);
// create recipient object
InternetAddress addressRecipients = new InternetAddress();
// create from object
InternetAddress addressFrom = new InternetAddress(from);
// Set Message content and properties
msg.setRecipients(Message.RecipientType.TO, addressRecipients.parse(tos));
msg.setRecipients(Message.RecipientType.CC, addressRecipients.parse(ccs));
msg.setRecipients(Message.RecipientType.BCC, addressRecipients.parse(bcs));
msg.setFrom(addressFrom);
msg.setSubject(subject);
msg.setContent(content, "text/plain");
// Send Message
Transport.send(msg);
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = smtpAuthUser;
String password = smtpAuthPassword;
return new PasswordAuthentication(username, password);
}
}
/**
* Validate an email address. Parse the given string and find the email
* address and check it complies to the RFC822 standard
*
* @param text
* @return boolean
* @throws IllegalArgumentException
* if a text param is null or empty if email is null
*/
public static boolean validateEmail(String text, StringBuffer email) {
if (text == null && text.equals(""))
throw new IllegalArgumentException("text parameter is empty");
if (email == null)
throw new IllegalArgumentException("email parameter is empty");
// String text = "duncanmorton@rapide.co.uk";
System.out.println(text);
String[] textValues = text.split(" ");
boolean validEmail = false;
for (int i = 0; i < textValues.length; i++) {
try {
System.out.println(textValues[i]);
if (isValidEmailAddress(textValues[i])) {
email.append(textValues[i]);
return true;
}
} catch (AddressException e) {
// Invalid email found. This is thrown by isValidEmailAddress
// for any string that is not a valid email
}
}
return validEmail;
}
/**
* Validate an email address. Check the email address complies to the RFC822
* standard and the address is in lowercase
*
* @param email
* @return boolean
* @throws AddressException
* - if the parsing failed
* @throws IllegalArgumentException
* if a email param does not comply.
*/
public static boolean isValidEmailAddress(String email) throws AddressException {
if (email == null && email.equals(""))
throw new IllegalArgumentException("email parameter is empty");
// *Parameters:
// *address - the address in RFC822 format
// *strict - enforce RFC822 syntax
InternetAddress emailAddr = new InternetAddress(email);
// Set the email pattern string
Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
// Match the given string with the pattern
Matcher m = p.matcher(email);
// check whether match is found
boolean matchFound = m.matches();
if (matchFound) {
return true;
} else {
return false;
}
}
static String SMTP_SERVER="";
static String ERROR_ALERT_EMAIL_ADDRESSES="dongnan.zheng@..";
static String EMAIL_FROM="..@..";
static String SERVICE_NAME="L....";
public static void main( String... aArguments ){
Emailer emailer = new Emailer(SMTP_SERVER);
try {
emailer.send(ERROR_ALERT_EMAIL_ADDRESSES, EMAIL_FROM, "",
"", SERVICE_NAME, "testemail");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
*********************************************************************************
运行测试报java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream 。
原因:
MyEclipse6.5的javaee.jar中的mail包与JavaMail包有冲突。
J2EE5中mail.jar包定义的只是接口,没有实现,是不能真正发送邮件的,但开发编译肯定是可以过去的,因为我们是针对J2EE规范编的程 序。而运行期用Sun公司的JavaMail1.4的实现才可以开始发送邮件,
解决:
在MyEclipse目录下,找javaee.jar包,用WinRar打开,删除里面的mail目录
Comments
Post a Comment