Статьи

Отправка электронной почты с Java (Осторожно)

Я включаю отладку, чтобы отследить, что происходит. Все выглядит хорошо, но одна электронная почта приходит в себя через день, а некоторые горячие и gmail просто исчезают.

Чтобы проверить почтовый сервер с одного из наших серверов UNIX:

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.*;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
public class Mail {

 /// example command line run
 public static void main(String[] args) {
String sArray[] = new String[] {"[email protected]", "[email protected]", "[email protected]"};
List<String> emails = Arrays.asList(sArray);
 Iterator<String> iterator = emails.iterator();
 while (iterator.hasNext()) {
 Mail.sendEmail("test from test", "message", iterator.next() );
}
}

/**
 * size of buffer
 */
 public static final int gkBUFFER_SIZE = 256;
/**
 * getCurrentDateTime
 * @return Date current date
 */
 public final static Date getCurrentDateTime() {
 return new Date(System.currentTimeMillis());
 }

/**
 * sendEmail
 * @param subject subject of email
 * @param message message text
 * @param emailAddress email address to send to
 * @return String log of errors/status
 */
 public final static String sendEmail(String subject, String message,
 String emailAddress) {
// email sent
 boolean emailSent = true;
// email message
 StringBuffer emailLoggingMessage =
 new StringBuffer(Mail.gkBUFFER_SIZE);
// start of message
 emailLoggingMessage
 .append("Email:")
 .append(emailAddress).append(System.getProperty("line.separator"));
// Email Properties
 Properties props = new Properties();
// add properties from properties file
 props.put("mail.smtp.host",
 "mymail.mydomain.com");
 props.put("mail.debug",
 "true");
 props.put("mail.smtp.port","25");
// -- login
 props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props,
 new javax.mail.Authenticator() {
 protected PasswordAuthentication getPasswordAuthentication() {
 return new PasswordAuthentication("nt domainntid", "ntpassword");
 }
 });

// / -------------
// turn on debug mode
 session.setDebug(true);
Message msg = new MimeMessage(session);
 InternetAddress addressFrom = null;
 try {
 addressFrom =
 new InternetAddress("[email protected]");
 } catch (AddressException e) {
 e.printStackTrace();
emailLoggingMessage.append(e.getLocalizedMessage()).append(
 System.getProperty("line.separator"));
 emailSent = false;
 }
 try {
 msg.setFrom(addressFrom);
 } catch (MessagingException e) {
 e.printStackTrace();
emailLoggingMessage.append(e.getLocalizedMessage()).append(
 System.getProperty("line.separator"));
 emailSent = false;
 }
// recipient
 InternetAddress addressTo = null;
 try {
 addressTo = new InternetAddress(emailAddress);
 } catch (AddressException e) {
 e.printStackTrace();
 // refactor this
 emailLoggingMessage.append(e.getLocalizedMessage()).append(
 System.getProperty("line.separator"));
 emailSent = false;
 }
// add to address as recipient
 try {
 msg.setRecipient(Message.RecipientType.TO, addressTo);
 } catch (MessagingException e) {
 e.printStackTrace();
 emailLoggingMessage.append(e.getLocalizedMessage()).append(
 System.getProperty("line.separator"));
 emailSent = false;
 }

// Setting the Subject and Content Type
 try {
 msg.setSubject(subject);
 } catch (MessagingException e) {
 e.printStackTrace();
 emailLoggingMessage.append(e.getLocalizedMessage()).append(
 System.getProperty("line.separator"));
 emailSent = false;
 }
 try {
 msg.setContent(message,"text/plain");
 } catch (MessagingException e) {
 e.printStackTrace();
 emailLoggingMessage.append(e.getLocalizedMessage()).append(
 System.getProperty("line.separator"));
 emailSent = false;
 }
 try {
 Transport.send(msg);
 } catch (MessagingException e) {
 e.printStackTrace();
 emailLoggingMessage.append(e.getLocalizedMessage()).append(
 System.getProperty("line.separator"));
 emailSent = false;
 }
// sent message
 if (emailSent) {
 emailLoggingMessage.append("Email successfully sent.")
 .append(System.getProperty("line.separator"));
 }
// return message
 return emailLoggingMessage.toString();
 }
}

Я тестирую на сервере UNIX с:

— mail.sh

export ANT_OPTS="-Xms2048m -Xmx2048m -XX:MaxPermSize=1024m"
export JAVA_OPTS="-server -Xms2048m -Xmx2048m -XX:MaxPermSize=1024m"
export CLASSPATH=$CLASSPATH:dsn.jar:mail.jar:mailapi.jar:pop3.jar:smtp.jar:activation.jar:imap.jar:ojdbc14.jar:runtime12.jar:.
javac Mail.java
java Mail > mail.txt 2&> mailerr.txt

Журнал отладки

DEBUG: JavaMail version 1.4.4
DEBUG: URL jar:file:/home/tspann/mail/pop3.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: jar:file:/home/tspann/mail/pop3.jar!/META-INF/javamail.providers
DEBUG: URL jar:file:/home/tspann/mail/smtp.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: jar:file:/home/tspann/mail/smtp.jar!/META-INF/javamail.providers
DEBUG: URL jar:file:/home/tspann/mail/imap.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: jar:file:/home/tspann/mail/imap.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name:
{com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc],
com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc],
com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc],
com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc],
com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc],
com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc],
imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,
com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsy stems, Inc],
smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc],
pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: URL jar:file:/home/tspann/mail/smtp.jar!/META-INF/javamail.address.map
DEBUG: successfully loaded resource: jar:file:/home/tspann/mail/smtp.jar!/META-INF/javamail.address.map
DEBUG: setDebug: JavaMail version 1.4.4
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "SomeSenderDomain.com", port 25, isSSL false
220 SomeSenderDomain.com SMTP Ready.
DEBUG SMTP: connected to host "SomeSenderDomain.com", port: 25

EHLO timspann.cool.com
250-ESMTP Server Ready
250-SIZE 0
250-DSN
250-STARTTLS
250 TLS
DEBUG SMTP: Found extension "SIZE", arg "0"
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "TLS", arg ""
DEBUG SMTP: use8bit false
MAIL FROM:<[email protected]>
250 +OK Sender OK
RCPT TO:<[email protected]>
250 +OK Recipient OK
DEBUG SMTP: Verified Addresses
DEBUG SMTP: [email protected]
DATA
354 Start mail input, end with '<CR><LF>.<CR><LF>'
From: [email protected]
To: [email protected]
Message-ID: <[email protected]>
Subject: test from test
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

message
.
250 +OK message queued for delivery.
QUIT
221 Service closing transmission channel closing connection

Проблемы с IBM AIX Websphere JDK

JavaMail API
транспорта
FSQ
Обзор
Javamail Документы
Javamail Docs2
Javamail Readme
Обзор SMTP-пакетов
JavaMail без сервера
JavaMail

Проблемы IBM с SSL TLS / GMAIL

Тонкий клиент
IBM WAS security

Файл java.security в / base_v61 / java / jre / lib / security

Порт 25
Gmail Порты
SMTP
Ошибки SMTP
Javamail с SMTPS / SSL
Gmail SMTP с использованием SSL
Javamail для Hotmail
SSL — Android
STARTTTLS
Javamail от Websphere
Отправка Gmail
Сертификат ошибки SSL
Поддержка
IBM Поддержка
IBM Поддержка IBM

Javamail с TLS в AIX

SSL