通过javamail从办公室邮件发送电子邮件

时间:2017-10-20 06:13:41

标签: java email javamail

我正在通过Gmail发送电子邮件,但当我尝试从公司邮件发送电子邮件时,我会遇到异常。

从公司邮件中我可以发送电子邮件给其他员工邮件,但当我尝试发送到gmail帐户时,我收到javax.mail.SendFailedException:无效的地址;   嵌套异常是:     com.sun.mail.smtp.SMTPAddressFailedException:550 5.7.1无法中继异常。 我该如何解决?

通过gmail

    final String username = "mail goes here";
    final String password = "password goes here";

    final String to = "mail goes here";
    final String from = username;

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.ssl.trust", "smtp.gmail.com");

    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(toGmail));
        message.setSubject("Test");
        message.setText("Testing");
        Transport.send(message);
        System.out.println("Mail sent succesfully");
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

通过公司邮件

    final String toGmail = "test@gmail.com";
    final String toCompany = "one of employees mail goes here";
    final String from = "company's noreply mail goes here";
    final String to = toGmail;

    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.port", "25");
    props.put("mail.smtp.host", "10.100.25.5");
    props.setProperty("mail.debug", "true");

   // props.put("mail.smtp.auth", "true");
   // props.put("mail.smtp.starttls.enable", "true");
   // props.put("mail.smtp.ssl.enable", "true");

    Session session = Session.getInstance(props);

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(to));
        message.setSubject("Test");
        message.setText("Testing");
        Transport.send(message);
        System.out.println("Mail sent succesfully");
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

1 个答案:

答案 0 :(得分:0)

答案在JavaMail FAQ。您未对公司邮件服务器进行身份验证,因此不允许您在公司外部发送邮件。