Всем добрый вечер. У меня не получается отправить сообщение на аккаунт gmail (на mail.ru отправляеться без проблем). Вот код:
| Код | protected boolean sendEmail(String smtphost, String to, String from, String subj, String text, String patch) throws Exception { if (smtphost == null) smtphost = "sdfdfdf@mail.ru"; if (from == null) from = "xxx"; if (to == null) { System.err.println("sendEmail. Вы не указали получателя сообщения"); throw new NullPointerException("Вы не указали получателя сообщения"); } if (subj == null) { System.err.println("sendEmail. Вы не указали тему сообщения"); throw new NullPointerException("Вы не указали тему сообщения"); } boolean rez = false; try { // создаём сообщение и выставляем общие свойства Properties mailProps = new Properties(); mailProps.setProperty("mail.smtp.host", smtphost); mailProps.setProperty("mail.smtp.auth", "true"); mailProps.setProperty("mail.smtp.debug", "true"); mailProps.setProperty("mail.smtp.port", "25"); mailProps.setProperty("mail.password", pass); mailProps.setProperty("mail.transport.protocol", "smtp"); mailProps.setProperty("mail.user", user); mailProps.put("mail.smtp.starttls.enable", "true");//for gmail //mailProps.put("mail.smtp.socketFactory.port", smtphost); //mailProps.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); //mailProps.put("mail.smtp.socketFactory.fallback", "false"); Session session = Session.getDefaultInstance(mailProps, new javax.mail.Authenticator() { public javax.mail.PasswordAuthentication getPasswordAuthentication() { return new javax.mail.PasswordAuthentication(user, pass); } }); MimeMessage mail = new MimeMessage(session); mail.setFrom(new InternetAddress(from)); mail.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); mail.setSubject(subj, "koi8-r"); mail.setHeader("content-type", "text/html; charset=windows-1251"); mail.setSentDate(new Date()); // часть письма с текстом Multipart mp = new MimeMultipart(); MimeBodyPart txt = new MimeBodyPart(); txt.setText(text); mp.addBodyPart(txt); // часть письма с файлом if (patch != null) { MimeBodyPart fileAtt = new MimeBodyPart(); fileAtt.setDataHandler(new DataHandler(new FileDataSource(patch))); StringTokenizer st = new StringTokenizer(patch, "/"); String fname = ""; while (st.hasMoreElements()) { fname = st.nextToken(); } fileAtt.setFileName(fname); mp.addBodyPart(fileAtt); } // добавляем обе части в письмо mail.setContent(mp); Transport.send(mail);
Transport transport = session.getTransport("smtp"); transport.connect(smtphost, user, pass); transport.sendMessage(mail, mail.getAllRecipients()); transport.close(); rez = true; } catch (Exception ex) { System.err.print("~~~~ Сообщение не отправлено: " + ex.getMessage()); ex.printStackTrace(); } return rez; }
|
Кто может что посоветовать? |