Я использую javamail, чтобы попытаться получить почту из своего почтового ящика.
Я использую виртуальную машину redhat, на которой я смонтировал свой почтовый сервер, а затем на моем локальном компьютере я подключаюсь к roundcube 192.168.137.32/roundcube. и я могу отправлять и получать там письма.
Теперь на моем dev vm я пытаюсь использовать javamail api для получения моих почтовых ящиков, но получаю это сообщение об ошибке:
Exception in thread "main" javax.mail.MessagingException: Remote host terminated the handshake;
nested exception is:
javax.net.ssl.SSLHandshakeException: Remote host terminated the handshake
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:742)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at ban.sante.efs.mailing.ReceiveMailImap2.doit(ReceiveMailImap2.java:36)
at ban.sante.efs.mailing.ReceiveMailImap2.main(ReceiveMailImap2.java:159)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
Caused by: javax.net.ssl.SSLHandshakeException: Remote host terminated the handshake
at java.base/sun.security.ssl.SSLSocketImpl.handleEOF(SSLSocketImpl.java:1321)
at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1160)
at java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1063)
at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:402)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:626)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:400)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:134)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:131)
at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:763)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:698)
... 9 more
Caused by: java.io.EOFException: SSL peer shut down incorrectly
at java.base/sun.security.ssl.SSLSocketInputRecord.decode(SSLSocketInputRecord.java:167)
at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:108)
at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1152)
... 18 more
Вот мой Java класс:
public ReceiveMailImap2()
{
}
public static void doit() throws MessagingException, IOException
{
Folder folder = null;
Store store = null;
try
{
final Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imap");
final Session session = Session.getDefaultInstance(props, null);
// session.setDebug(true);
store = session.getStore("imaps");
store.connect("mail.mydomain.com", "xxx@mydomain.com", "Passxxx");
folder = store.getFolder("Inbox");
/* Others GMail folders :
* [Gmail]/All Mail This folder contains all of your Gmail messages.
* [Gmail]/Drafts Your drafts.
* [Gmail]/Sent Mail Messages you sent to other people.
* [Gmail]/Spam Messages marked as spam.
* [Gmail]/Starred Starred messages.
* [Gmail]/Trash Messages deleted from Gmail.
*/
folder.open(Folder.READ_WRITE);
final Message[] messages = folder.getMessages();
System.out.println("No of Messages : " + folder.getMessageCount());
System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
for (int i = 0; i < messages.length; ++i)
{
System.out.println("MESSAGE #" + (i + 1) + ":");
final Message msg = messages[i];
/*
if we don''t want to fetch messages already processed
if (!msg.isSet(Flags.Flag.SEEN)) {
String from = "unknown";
...
}
*/
String from = "unknown";
if (msg.getReplyTo().length >= 1)
{
from = msg.getReplyTo()[0].toString();
} else if (msg.getFrom().length >= 1)
{
from = msg.getFrom()[0].toString();
}
final String subject = msg.getSubject();
System.out.println("Saving ... " + subject + " " + from);
// you may want to replace the spaces with "_"
// the TEMP directory is used to store the files
final String filename = "c:/temp/" + subject;
saveParts(msg.getContent(), filename);
msg.setFlag(Flags.Flag.SEEN, true);
// to delete the message
// msg.setFlag(Flags.Flag.DELETED, true);
}
} finally
{
if (folder != null)
{
folder.close(true);
}
if (store != null)
{
store.close();
}
}
}
public static void saveParts(final Object content, String filename)
throws IOException, MessagingException
{
OutputStream out = null;
InputStream in = null;
try
{
if (content instanceof Multipart)
{
final Multipart multi = ((Multipart) content);
final int parts = multi.getCount();
for (int j = 0; j < parts; ++j)
{
final MimeBodyPart part = (MimeBodyPart) multi.getBodyPart(j);
if (part.getContent() instanceof Multipart)
{
// part-within-a-part, do some recursion...
saveParts(part.getContent(), filename);
} else
{
String extension = "";
if (part.isMimeType("text/html"))
{
extension = "html";
} else
{
if (part.isMimeType("text/plain"))
{
extension = "txt";
} else
{
// Try to get the name of the attachment
extension = part.getDataHandler().getName();
}
filename = filename + "." + extension;
System.out.println("... " + filename);
out = new FileOutputStream(new File(filename));
in = part.getInputStream();
int k;
while ((k = in.read()) != -1)
{
out.write(k);
}
}
}
}
}
} finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.flush();
out.close();
}
}
}
public static void main(final String[] args) throws Exception
{
ReceiveMailImap2.doit();
}
}
Мой postfix main.cf:
queue_directory = /var/spool/postfix
command_directory = /usr/sbin
daemon_directory = /usr/libexec/postfix
data_directory = /var/lib/postfix
mail_owner = postfix
myhostname = mail.xxx.com
mydomain = xxx.com
myorigin = $myhostname
inet_interfaces = all
inet_protocols = all
mydestination = $myhostname, localhost.$mydomain, localhost
smtpd_recipient_restrictions = permit_mynetworks
unknown_local_recipient_reject_code = 550
home_mailbox = Maildir/
debug_peer_level = 2
debugger_command =
PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
ddd $daemon_directory/$process_name $process_id & sleep 5
sendmail_path = /usr/sbin/sendmail.postfix
newaliases_path = /usr/bin/newaliases.postfix
mailq_path = /usr/bin/mailq.postfix
setgid_group = postdrop
html_directory = no
manpage_directory = /usr/share/man
sample_directory = /usr/share/doc/postfix-2.10.1/samples
readme_directory = /usr/share/doc/postfix-2.10.1/README_FILES
append_dot_mydomain = no
biff = no
config_directory = /etc/postfix
dovecot_destination_recipient_limit = 1
message_size_limit = 4194304
virtual_transport = dovecot
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
virtual_mailbox_domains = mysql:/etc/postfix/database-domains.cf
virtual_mailbox_maps = mysql:/etc/postfix/database-users.cf
virtual_alias_maps = mysql:/etc/postfix/database-alias.cf
А это конфигурация файла postfix master.cf:
smtp inet n - n - - smtpd
#smtp inet n - n - 1 postscreen
#smtpd pass - - n - - smtpd
#dnsblog unix - - n - 0 dnsblog
#tlsproxy unix - - n - 0 tlsproxy
submission inet n - n - - smtpd
-o syslog_name=postfix/submission
# -o smtpd_tls_security_level=encrypt
-o smtpd_sasl_auth_enable=yes
-o smtpd_reject_unlisted_recipient=no
# -o smtpd_client_restrictions=$mua_client_restrictions
# -o smtpd_helo_restrictions=$mua_helo_restrictions
# -o smtpd_sender_restrictions=$mua_sender_restrictions
-o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
# -o milter_macro_daemon_name=ORIGINATING
#smtps inet n - n - - smtpd
# -o syslog_name=postfix/smtps
# -o smtpd_tls_wrappermode=yes
-o smtpd_sasl_auth_enable=yes
-o smtpd_reject_unlisted_recipient=no
# -o smtpd_client_restrictions=$mua_client_restrictions
# -o smtpd_helo_restrictions=$mua_helo_restrictions
# -o smtpd_sender_restrictions=$mua_sender_restrictions#
-o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
-o milter_macro_daemon_name=ORIGINATING
#628 inet n - n - - qmqpd
pickup unix n - n 60 1 pickup
cleanup unix n - n - 0 cleanup
qmgr unix n - n 300 1 qmgr
#qmgr unix n - n 300 1 oqmgr
tlsmgr unix - - n 1000? 1 tlsmgr
rewrite unix - - n - - trivial-rewrite
bounce unix - - n - 0 bounce
defer unix - - n - 0 bounce
trace unix - - n - 0 bounce
verify unix - - n - 1 verify
flush unix n - n 1000? 0 flush
proxymap unix - - n - - proxymap
proxywrite unix - - n - 1 proxymap
smtp unix - - n - - smtp
relay unix - - n - - smtp
# -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq unix n - n - - showq
error unix - - n - - error
retry unix - - n - - error
discard unix - - n - - discard
local unix - n n - - local
#virtual unix - n n - - virtual
lmtp unix - - n - - lmtp
anvil unix - - n - 1 anvil
scache unix - - n - 1 scache
dovecot unix - n n - - pipe
flags=DRhu user=vmail:vmail argv=/usr/libexec/dovecot/deliver -f ${sender} -d ${recipient}
Также я использую конфигурационный файл roundcube:
<?php
$config['db_dsnw'] = 'mysql://roundcube_admin:Passwordxxx@localhost/roundcube';
$config['default_host'] = 'localhost';
$config['support_url'] = '';
$config['des_key'] = 'q4CjrPyqCM5yw4Ca6T2uwc5M';
$config['defautl_port'] = 143;
$config['smtp_server'] = 'localhost';
$config['smtp_port'] = 587;
$config['smtp_user'] = '%u';
$config['smtp_pass'] = '%p';
$config['smtp_auth_type'] = 'LOGIN';
$config['smtp_debug'] = true;
$config['plugins'] = array('virtuser_query');
$config['virtuser_query'] = "SELECT Email FROM postfix_accounts.accounts_table WHERE Email = '%u'";
$config['debug_level'] = 4;
$config['sql_debug'] = true;
$config['imap_debug'] = true;
$config['ldap_debug'] = true;
#$config['smtp_debug'] = true;
Примечание: я не добавлял никаких сертификатов на свой redhatvm. Я также могу без проблем пропинговать мою виртуальную машину redhat, на которой установлен постфикс, с моей виртуальной машины dev
Заранее большое спасибо.