我正在使用JavaMail和smtp(gmail),这是我的代码:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Email {
Properties emailProperties;
Session mailSession;
MimeMessage emailMessage;
public static void main(String args[]) throws AddressException,
MessagingException {
Email javaEmail = new Email();
javaEmail.setMailServerProperties();
javaEmail.createEmailMessage();
javaEmail.sendEmail();
}
public void setMailServerProperties() {
String emailPort = "587";//gmail's smtp port
emailProperties = System.getProperties();
emailProperties.put("mail.smtp.port", emailPort);
emailProperties.put("mail.smtp.auth", "true");
emailProperties.put("mail.smtp.starttls.enable", "true");
}
public void createEmailMessage() throws AddressException,
MessagingException {
String[] toEmails = { "to@gmail.com" };
String emailSubject = "Java Email";
String emailBody = "This is an email sent by JavaMail api.";
mailSession = Session.getDefaultInstance(emailProperties, null);
emailMessage = new MimeMessage(mailSession);
for (int i = 0; i < toEmails.length; i++) {
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
}
emailMessage.setSubject(emailSubject);
emailMessage.setContent(emailBody, "text/html");//for a html email
//emailMessage.setText(emailBody);// for a text email
}
public void sendEmail() throws AddressException, MessagingException {
String emailHost = "smtp.gmail.com";
String fromUser = "yourusername";//just the id alone without @gmail.com
String fromUserEmailPassword = "your_password";
Transport transport = mailSession.getTransport("smtp");
transport.connect(emailHost, fromUser, fromUserEmailPassword);
transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
transport.close();
System.out.println("Email sent successfully.");
}
}
错误讯息:
Exception in thread "main" javax.mail.MessagingException: 530 5.7.0
Must issue a STARTTLS command first. n80sm23847952pfi.25 - gsmtp
at
com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:1020)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:716)
at
com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:388)
at com.mail.Email.sendEmail(Email.java:68) at
com.mail.Email.main(Email.java:26)
答案 0 :(得分:0)
您可以尝试更改此行:
Transport t = session.getTransport("smtps");
您必须提供所需的相应用户名和密码 你的邮件服务器。请注意,您可以将协议更改为&#34; smtps&#34;至 通过SSL建立安全连接。
此处的完整信息:http://www.oracle.com/technetwork/java/javamail/faq/index.html#gmail
答案 1 :(得分:0)
在我的情况下,当我使用ibm-was - * .jar时出现上述问题。当我将jar切换到Javax.mail-version.jar时,它得到了解决(版本是1.5.5之类的数字)。