我无法通过Gmail发送含有Java代码的电子邮件。无法通过Gmail使用Java发送电子邮件
CODE:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class b {
public static void sendMessage(String to, String from, String subject, String text){
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "false");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.transport.protocol", "smtp");
Session session = Session.getInstance(props, null);
try {
Message message = new MimeMessage(session);
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(subject);
message.setText(text);
Transport transport = session.getTransport("smtp");
String mfrom = "fromemail";
transport.connect("smtp.gmail.com", mfrom, "fromemailpassword");
transport.sendMessage(message, message.getAllRecipients());
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
我得到的错误:
javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. b3sm24500496wiw.22 - gsmtp
我试图从Gmail帐户发送电子邮件到一个Gmail户头都没有成功。我需要为我的商业电子邮件发送邮件通讯等。
编辑:
我改的一段代码到这一点:
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "25");
properties.put("mail.smtp.auth", "true"); //make it true
properties.put("mail.smtp.starttls.enable", "true"); //make it true
properties.put("mail.smtp.ssl.trust", "smtp.gmail.com");
//Authentication is needed use your gmail user and password"smtp.gmail.com"
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]", "password");
}
};
Session session = Session.getInstance(properties, auth);
现在我得到异常: javax.mail.AuthenticationFailedException
你先试试谷歌搜索?很多网络的例子。请参阅[常见问题]需要先搜索 – tgkprog 2014-08-29 10:06:26
[JavaMail smtp属性(适用于STARTTLS)](http://stackoverflow.com/questions/5592112/javamail-smtp-properties-for-starttls) – tgkprog 2014-08-29 10:07:54