0

I need to send mail from my gmail account to another. I used the following code.

               String fromaddress = "xxx@gmail.com"; 
    String password = "yyy";
    String hostname = "smtp.gmail.com";
    String hoststring = "mail.smtp.host";
    String toaddress = "yyy@gmail.com";
    String emailcontent;

    Properties properties = System.getProperties();
    properties.setProperty(hoststring, hostname);
    Session session = Session.getDefaultInstance(properties);

    try{
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromaddress));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(toaddress));
        message.setSubject("hi");
        emailcontent = "hi...";
        message.setText(emailcontent);
        System.out.println(emailcontent);
        Transport.send(message);
        System.out.println("Sent....");
    }catch (MessagingException mex) 
    {
        mex.printStackTrace();
    }

But i get the error as follows... javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25

How am i to solve this. Can you please help me out.

4

3 に答える 3

1

ポート番号を変更する必要があると思います。25~587

あなたはから助けを得ることができます

http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/

Gmail 設定ヘルプ リンク:

http://gmailsmtpsettings.com/

于 2013-05-03T08:59:29.393 に答える
1
public static void sendEmail(Email mail) {

    String host = "smtp.gmail.com";
    String from = "YOUR_GMAIL_ID";
    String pass = "YOUR_GMAIL_PASSWORD";
    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", "true"); // added this line
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");

    // Get the default Session object.
    Session session = Session.getDefaultInstance(props, null);

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set sender
        message.setFrom(new InternetAddress("Senders_EMail_Id"));

        // Set recipient
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("RECIPIENT_EMAIL_ID"));

        // Set Subject: header field
        message.setSubject("SUBJECT");

        // set content and define type
        message.setContent("CONTENT", "text/html; charset=utf-8");

        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
      } catch (MessagingException mex) {
        System.out.println(mex.getLocalizedMessage());
    }

}

}`

これでうまくいくはずだと思います。

于 2013-05-03T09:53:16.510 に答える