Показаны сообщения с ярлыком Java. Показать все сообщения
Показаны сообщения с ярлыком Java. Показать все сообщения

суббота, 15 октября 2016 г.

Почтовое сообщение по протоколу SMTP из Java с использованием SSL

Собственно нужно было послать. Из программы. С почтового ящика на Yandex. А Яндекс перешёл на SSL

Что характерно копи-паст из интернета ничего не дал. Все время вылазили исклчючения. Или письма вроде как уходили, но в ящик не приходили.
Полез сюда в раздел Programming на oracle.com. Нашёл вот такое:

Q: What are some of the most common mistakes people make when using JavaMail? A: Unfortunately, the internet is full of copy and paste programmers who don't understand the code they're using, which has resulted in a lot of unnecessarily complex and often incorrect examples. The most common mistakes are:
  • Use of Session.getDefaultInstance. Almost all code should use Session.getInstanceinstead, as described below
  • Calling the send method on a Transport instance variable. As described belowsend is a static method and ignores the Transport instance you use to call it.
  • Setting various socketFactory properties. Long, long ago JavaMail didn't have built in support for SSL connections, so it was necessary to set these properties to use SSL. This hasn't been the case for years; remove these properties and simplify your code. The easiest way to enable SSL support in current versions of JavaMail is to set the property "mail.smtp.ssl.enable" to "true". (Replace "smtp" with "imap" or "pop3" as appropriate.)
  • Using an Authenticator just to supply a username and password. There's really nothing wrong with using an Authenticator, it's just unnecessarily complex. A more straightforward approach is to call the connect method that takes a username and password when connecting to a Store. When sending a message, use the static Transport.send method that takes a username and password.
что характерно, прямо про меня.
Последовал рекомендациям и о чудо все получилось. Приведу функцию полностью как она работает у меня:
    public void sendMail(String paramTo, String paramSubject, String paramBody)
    {
        try
        {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.yandex.ru");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");
            props.put("mail.smtp.ssl.enable","true");
            Session session = Session.getInstance(props);
           
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("my_mailbox@yandex.ru"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(paramTo.trim()));
            message.setContent("This is a test", "text/plain");
            message.setSubject(paramSubject);
            message.setText(paramBody);
            Transport.send(message,"user_name", "user_password");
            System.out.println("Sent message successfully....");
        } catch (Exception mex)
        {
            System.out.println("******* ERROR sending Email *******");
            mex.printStackTrace();
        }
    }
Тащемта всё.



Лучший поставщик комплектующих

среда, 28 октября 2015 г.

12705: Cannot access NLS data files or invalid environment specified

NetBeans 8.0.2.
Windows 10 x64

При попытке создать соединение через драйвер ojdbc7 появляется ошибка

невозможно соединиться с jdbc:oracle:thin:@localhost:1521:XE с помощью oracle.jdbc.OracleDriver (ORA-00604: error occurred at recursive SQL level 1 ORA-12705: Cannot access NLS data files or invalid environment specified )

В файле

C:\Program Files\NetBeans 8.0.2\etc\netbeans.conf

в строке

netbeans_default_options

в кавычки необходимо добавить опцию

-J-Duser.region=US

Это решает проблему. Если вместо US поставить RU то проблема остаётся.


Похожая проблема при запуске приложения на сервере GlassFish

Severe:   Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: ORA-00604: error occurred at recursive SQL level 1
ORA-12705: Cannot access NLS data files or invalid environment specified


Тут она решается правкой конфигурационного файла домена

..\glassfish\domains\domain1\config\domain.xml

в секции

<java-config ="classpath-suffix="" debug-options="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=9009" system-classpath">

нужно вставить опцию

<jvm-options>-Duser.region=US</jvm-options>

и перезапустить сервер