JavaMail note

Introduction

Use Java Mail to send mail,need to rely on the package mail-X-X.X.jar.html

Download mail.jar:http://www.oracle.com/technetwork/java/javamail/index-138643.htmljava

JavaMail API Documentation:https://javamail.java.net/nonav/docs/api/api

Core member class

Session、Message、Address、Transportsession

Session:The Session class represents a mail session and is not subclassed. It collects together properties and defaults used by the mail API's.oracle

Message:This class models an email message. This is an abstract class. Subclasses provide actual implementations. Direct Known Subclasses: MimeMessage.socket

Address:This abstract class models the addresses in a message. Subclasses provide specific implementations. Direct Known Subclasses: InternetAddressNewsAddresside

Transport:An abstract class that models a message transport. Subclasses provide actual implementations.Direct Known Subclasses:SMTPTransportspa

RecipientType.net

public static class RecipientType implements Serializable {
	/**
	 * The "To" (primary) recipients.
	 */
	public static final RecipientType TO = new RecipientType("To");
	/**
	 * The "Cc" (carbon copy) recipients.
	 */
	public static final RecipientType CC = new RecipientType("Cc");
	/**
	 * The "Bcc" (blind carbon copy) recipients.
	 */
	public static final RecipientType BCC = new RecipientType("Bcc");
    ...
}

Example

public void sendMail(String host, String port, String protocol, boolean sslConnect, 
			final String mail, final String password, String title, String content, List<String> receivers) {
		Session session = createSession(host, port, protocol, mail, password, sslConnect);
		
		try {
			Transport transport = session.getTransport();
			transport.connect(host, mail, password);
			MimeMessage message = createMessage(mail, title, content, receivers, session);
			transport.send(message, message.getAllRecipients());
			transport.close();
		} catch (NoSuchProviderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private MimeMessage createMessage(final String mail, String title,
			String content, List<String> receivers, Session session)
			throws MessagingException, AddressException {
		MimeMessage message = new MimeMessage(session);

		message.setFrom(new InternetAddress(mail));
		InternetAddress[] toAddresses = getReceivers(receivers);
		if (toAddresses == null) new IllegalArgumentException("There must be the recipient.");
		message.addRecipients(RecipientType.TO, toAddresses);

		message.setSubject(title);
		message.setSentDate(Calendar.getInstance().getTime());

		Multipart multipart = new MimeMultipart();
		BodyPart contentPart = new MimeBodyPart();
		contentPart.setContent(content, MESSAGE_TYPE);
		multipart.addBodyPart(contentPart);

		message.setContent(multipart);
		message.saveChanges();
		return message;
	}

	private InternetAddress[] getReceivers(List<String> receivers) {
		InternetAddress[] toAddresses = null;
		if (receivers != null && !receivers.isEmpty()) {
			toAddresses = new InternetAddress[receivers.size()];
			try {
				for (int i = 0; i < receivers.size(); i++)
					toAddresses[i] = new InternetAddress(receivers.get(i));
			} catch (AddressException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return toAddresses;
	}
	
	private Session createSession(String host, String port,
			String protocol, final String mail, final String password, boolean sslConnect) {
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", protocol); 
		props.setProperty("mail.smtp.host", host);
		props.setProperty("mail.smtp.port", port);
		props.put("mail.smtp.auth", "true");
        if (sslConnect) {
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			props.put("mail.smtp.socketFactory.fallback", "false");
            props.put("mail.smtp.socketFactory.port", port);
		}
		Session session = Session.getDefaultInstance(props, new Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(mail, password);
					}
				});
		session.setDebug(true);
		return session;
	}

When the configuration parameter errors, such as "smtp.port", only after a timeout will return an error message. The default timeout is 5 minutes.code

Configure the connection timeout: 10 second

props.put("mail.smtp.connectiontimeout", 10000); //millisecond

Configure the send timeout: 10 second

props.put("mail.smtp.timeout", 10000); //millisecond

Timeout will throw the following exception

javax.mail.MessagingException: java.net.SocketTimeoutException: Read timed out

If the timeout configuration does not take effect, check the mail version. Version 1.5 includes more than 1.5 version can be successful. 《http://stackoverflow.com/questions/18970409/why-javamail-connection-timeout-is-too-long》

相關文章
相關標籤/搜索