如何使用Javamail发送简单的电子邮件?

时间:2016-06-09 09:09:55

标签: java email javamail

我正在创建一个简单的java邮件程序,该程序工作正常,最后一个系统打印也正常工作。但问题是我收到了outlook.here中的邮件我正在使用公司outlook.please一些人帮我。 我在这里附上我的代码

enter code here

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;




public class SimpleSendEmail 
{
    public static void main(String[] args) 

    {

        String host = "compny host";
        String from = "mail id";
        String to = "usr@some.com";
        String subject = "birthday mail";
        String messageText = "I am sending a message using the"
                + " simple.\n" + "happy birthday.";
        boolean sessionDebug = false;
        Properties props = System.getProperties();
        props.put("compny host", host);
        props.put("mail.smtp.port", "25");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.starttls.enable", "true");
        Session session = Session.getDefaultInstance(props, null);
        // Set debug on the Session so we can see what is going on
        // Passing false will not echo debug info, and passing true
        // will.
        session.setDebug(sessionDebug);
        try 
        {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            InternetAddress[] address = { new InternetAddress(to) };
            msg.setRecipients(Message.RecipientType.TO, address);
            msg.setSubject(subject);
            msg.setSentDate(new Date());
            msg.setText(messageText);

            Transport.send(msg);
            System.out.println("Sent message successfully....");
        } 

        catch (MessagingException mex)
        {
            mex.printStackTrace();
        }
    }
}



output
Sent message successfully....

2 个答案:

答案 0 :(得分:1)

“Compny host”似乎不是正确的主机。查看本教程http://www.tutorialspoint.com/java/java_sending_email.htm,此处您还有一些使用Java发送电子邮件的示例Send email using java

答案 1 :(得分:0)

我确实希望您使用正确的主机。

但您缺少用户名和密码。

transport = session.getTransport("smtp");
transport.connect(hostName, port, user, password);
transport.sendMessage(message, message.getAllRecipients());

或者您可以使用身份验证器:

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