我正在尝试使用我的java应用程序发送电子邮件,但它总是给我一个连接错误。所以我的代码看起来像这样:
public function addModelname(\Some\Where\Domain\Model\Modelname $modelname){...}
当然我提供了有效的信息(使用我的Gmail帐户)。这是我回来的错误:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendMail {
public static void main(String [] args) {
String to = "something@gmail.com";
String from = "fromsomeone@gmail.com";
String host = "localhost";
Properties properties = System.getProperties();
properties.setProperty("mail.user", "fromsomeone");
properties.setProperty("mail.password", "passwordForSomeone");
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("subject typed");
message.setText("This is actual message which is just some lines");
Transport.send(message);
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
有人可以帮助我,我的代码出了什么问题?谢谢!
答案 0 :(得分:1)
这将有助于您通过Gmail帐户发送邮件;
public class MailMan {
Session session = null;
public MailMan() {
if (session == null) {
init();
}
}
public void init() {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("EMAIL", "PASSWORD");
}
});
if (session != null) {
System.out.println("[OK]");
} else {
System.out.println("[NOK]");
}
}
public void sendMail() {
if (session == null) {
System.exit(0);
}
try {
String messageText = "";
Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress("no-reply", "No Reply"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
message.setReplyTo(InternetAddress.parse("no-reply"));
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("to_email"));
message.setSubject("TEST");
message.setText(messageText);
Transport.send(message);
System.out.println("[OK]");
} catch (MessagingException e) {
e.printStackTrace();
System.out.println("Not Sent...");
}
}
}
主要班级;
public class SendMail {
public static void main(String[] args) {
MailMan ma = new MailMan();
ma.sendMail();
}
}
毕竟你应该打开“访问不太安全的应用程序”。
答案 1 :(得分:0)
你可以尝试改变:
properties.setProperty("mail.smtp.host", host);
为:
properties.setProperty("mail.smtp.host", "smtp.gmail.com");