2015-02-26 3 views
0

Я прошел свой день, чтобы узнать, как отправлять почту с javamail 1.5.1 с использованием сервера обмена Microsoft Exchange, и я не нашел решения для своего проекта.Как отправить почту с помощью javamail 1.5.1 с помощью сервера обмена Microsoft Exchange?

public static void sendMail(String message_dest,String message_objet,String message_corps){ 

    Authenticator auth; 
    Session session; 
    Message mesg; 

    Properties props = new Properties(); 

    props.put("mail.transport.protocol", "smtp"); 
    props.put("mail.smtp.port", "25"); 
    props.put("mail.smtp.host", "10.X.X.X"); 
    props.put("mail.smtp.auth", "true"); 

    //Authenticator auth = new MyAuthentificator(); 
    auth = new javax.mail.Authenticator() { 
    protected PasswordAuthentication getPasswordAuthentication() { 

     return new PasswordAuthentication(
      "[email protected]", "xx"); 
    } 
    }; 

    session = Session.getDefaultInstance(props, auth); 

    session.setDebug(true); 

    try { 
    mesg = new MimeMessage(session); 

    mesg.setFrom(new InternetAddress([email protected])); 

    InternetAddress toAddress = new InternetAddress(message_dest); 
    mesg.addRecipient(Message.RecipientType.TO, toAddress); 

    mesg.setSubject(message_objet); 

    mesg.setText(message_corps); 

    Transport.send(mesg); 

    } catch (MessagingException ex) { 
    while ((ex = (MessagingException)ex.getNextException()) != null) { 
     ex.printStackTrace(); 
    } 
    } 
} 

Я уже пытаюсь выйти мою аутентификацию в другом классе, но это не будет работать слишком ...

Пожалуйста, помогите :(

PS: Извините за мой английский. ..

+2

Вы не указали какую-либо информацию о том, как он не работает, поэтому трудно догадаться, что происходит. Возможно, вы не указали правильное имя пользователя или пароль? Начните с очистки этих [распространенных ошибок] (http://www.oracle.com/technetwork/java/javamail/faq/index.html#commonmistakes), а затем опубликуйте [вывод отладки JavaMail] (http: // www. oracle.com/technetwork/java/javamail/faq/index.html#debug). –

ответ

0

Смотрите, если это работает:

import java.util.Properties; 
    import java.util.concurrent.ExecutorService; 
    import java.util.concurrent.Executors; 
    import java.util.concurrent.atomic.AtomicInteger; 
    import javax.activation.DataHandler; 
    import javax.activation.DataSource; 
    import javax.activation.FileDataSource; 
    import javax.mail.BodyPart; 
    import javax.mail.Message; 
    import javax.mail.Multipart; 
    import javax.mail.Session; 
    import javax.mail.Transport; 
    import javax.mail.internet.MimeBodyPart; 
    import javax.mail.internet.MimeMessage; 
    import javax.mail.internet.MimeMultipart; 

    public class EmailSenderWWOAttachment { 

    private static final int MSGCOUNT = 10; 
    static AtomicInteger c = new AtomicInteger(); 
    static Session session; 

    static class Sender implements Runnable { 
     @Override 

     public void run() { 
      while(c.get()<MSGCOUNT){ 
       int i = c.incrementAndGet(); 
       try { 
        // email without attachment 
        MimeMessage msg1 = new MimeMessage(session); 
        msg1.setFrom("[email protected]"); 
        msg1.setRecipients(Message.RecipientType.TO, "[email protected]"); 
        msg1.setSubject("Subject of email: " + i); 
        msg1.setText("Body of email: " + i); 
        Transport.send(msg1); 
        System.out.println("Email no. " + i + " without attachment sent"); 

        // email with attachment 
        MimeMessage msg = new MimeMessage(session); 
        msg.setFrom("[email protected]"); 
        msg.setRecipients(Message.RecipientType.TO, "[email protected]"); 
        msg.setSubject("Subject of email: " + i); 
        BodyPart messageBodyPart = new MimeBodyPart(); 
        messageBodyPart.setText("Body of email: " + i); 
        Multipart multipart = new MimeMultipart(); 
        multipart.addBodyPart(messageBodyPart); 
        BodyPart attachBodyPart = new MimeBodyPart(); 
        String filename = "C:\\Users\\user1\\Desktop\\1.txt"; 
        DataSource source = new FileDataSource(filename); 
        attachBodyPart.setDataHandler(new DataHandler(source)); 
        attachBodyPart.setFileName("1.txt"); 
        multipart.addBodyPart(attachBodyPart); 
        msg.setContent(multipart); 
        Transport.send(msg); 
        System.out.println("Email no. " + i + " with attachment sent"); 
       } catch (Exception e) { 
        e.printStackTrace(); 
        c.decrementAndGet(); 
       } 
      } 
     } 
    } 

    public static void main(String[] args) { 
     Properties props = new Properties(); 
     props.put("mail.smtp.host", "exchange-server"); 
     session = Session.getInstance(props, null); 

     ExecutorService executorService = Executors.newFixedThreadPool(20); 
     for(int i=0; i<20; i++) { 
      executorService.execute(new Sender()); 
     } 
     executorService.shutdown(); 
    } 
} 
0

Там нет аутентификации в вашей опции talib2608 :(Но я посмотрел на эти ссылки, и теперь моя аутентификация работает нормально. (Спасибо законопроект Shannon)

http://www.oracle.com/technetwork/java/javamail/faq/index.html#commonmistakes http://www.oracle.com/technetwork/java/javamail/faq/index.html#debug

public static void sendMail(String message_dest,String message_objet,String message_corps){ 

    Authenticator auth; 
    Session session; 
    Message mesg; 

    Properties props = new Properties(); 

    props.put("mail.transport.protocol", "smtp"); 
    props.put("mail.smtp.port", SMTP_PORT1); 
    props.put("mail.smtp.host", SMTP_HOST1); 
    props.put("mail.smtp.auth", "true"); 
    props.put("mail.smtp.ssl.enable", "true"); 

    session = Session.getInstance(props); 

    session.setDebug(true); 

    try { 
    mesg = new MimeMessage(session); 

    mesg.setFrom(new InternetAddress(IMAP_ACCOUNT1)); 

    InternetAddress toAddress = new InternetAddress(message_dest); 
    mesg.addRecipient(Message.RecipientType.TO, toAddress); 

    mesg.setSubject(message_objet); 

    mesg.setText(message_corps); 

    Transport t = session.getTransport("smtp"); 
    try { 
     t.connect("[email protected]", "mypwd"); 
     t.sendMessage(mesg, mesg.getAllRecipients()); 
    } finally { 
     t.close(); 
    } 

    }catch (MessagingException ex){ 
    System.out.println(ex); 
    } 
} 

Но когда я пытаюсь это, я не получаю мое сообщение ...

DEBUG: setDebug: JavaMail version 1.5.2 
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle] 
DEBUG SMTP: useEhlo true, useAuth true 
DEBUG SMTP: trying to connect to host "xx.xx.xxx.xx", port 25, isSSL true 
javax.mail.MessagingException: Could not connect to SMTP host: xx.xx.xxx.xx, port: 25; 
    nested exception is: 
    java.net.SocketException: Connection reset 

Это сообщение об ошибке возникает, когда я проверить на мой локальный компьютер, а не на сервере.

Смежные вопросы