在property.setProperty中获取语法错误(" mail.smtp.host",host);

时间:2016-11-17 08:46:50

标签: java selenium smtp

我在尝试通过SMTP发送邮件时获取以下行的语法。我在谷歌尝试但没有得到任何相关的答案。

property.setProperty(" mail.smtp.host",主机);

CODE:

public class SendMail {

//Recipient Mail id 
String to = "Receiver Mail ID";
//Sender Mail Id
String from = "Sender Mail ID";
//Sending email from the localhost
String host = "localhost";
//Get System Properties
Properties property = System.getProperties();
//Setup the mail server
property.setProperty("mail.smtp.host",host);
property.setProperty("mail.smtp.port" , "465");
//property.put("mail.smtp.auth", "true"); 
//Get the default session object
Session session = Session.getDefaultInstance(property);


try
{
    //Create a default MimeMessage object.
    MimeMessage message = new MimeMessage(session);
    //Set From: header field of the header
    message.setFrom(new InternetAddress(from));
    //Set To : header field of the header
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

    //Set Subject : header field
    message.setSubject("Automation Testing Report");

    //Create the Message part
    BodyPart messageBodypart = new MimeBodyPart();

    //Enter the message in the Mail Body
    messageBodypart.setText("***********Find the below for the Report****************");

    //Create a Multipart Message
    Multipart multipart = new MimeMultipart();

    //Set Text message part
    multipart.addBodyPart(messageBodypart);


    //Part two is attachment
    /*create the Message part*/
    messageBodypart = new MimeBodyPart();
    String filename = "E:\\Project\\jar\\Selenium        Scripts\\Hybrid_Driven\\test-output\\emailable-report.html";
    DataSource source = new FileDataSource(filename);
    messageBodypart.setDataHandler(new DataHandler(source));
    messageBodypart.setFileName(filename);
    //set the text message part
    multipart.addBodyPart(messageBodypart);

    //Send the complete message part
    message.setContent(multipart);


    //Send message 
    Transport.send(message);
    System.out.println("Mail has sent successfully");

}

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

}

}

请帮我解决此问题。

1 个答案:

答案 0 :(得分:1)

您无法将Java代码直接放入类中。它需要在方法内。编译器很乐意接受以下内容:

public class SendMail {

  ...

  //Get System Properties
  java.util.Properties property = System.getProperties();

  void doSomething()
  {
    property.setProperty("mail.smtp.host", host);
    property.setProperty("mail.smtp.port", "465");
    ...

  }
}