通过java程序详细发送邮件

时间:2013-07-25 14:34:17

标签: java-ee

我无法发送电子邮件我认为可能存在一些问题,请您查看代码

*import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
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 Mail {

    public static void sendReminder(String Message) throws AddressException, MessagingException{

          String to="jackson123@gmail.com";
          String password="784518";
          String from = "michal@gmail.com";
          String subject = "Reminder";



          String body = "Dear Sir";
          Properties props = new Properties(System.getProperties());
          // -- Attaching to default Session, or we could start a new one --
          props.put("mail.smtp.host", "smtp.gmail.com");
          SMTPAuthenticator smtpAuth = null;
          Session session = Session.getDefaultInstance(props, smtpAuth);
          // -- Create a new message --
          javax.mail.Message msg = new MimeMessage(session);
          // -- Set the FROM and TO fields --
          try {
            msg.setFrom(new InternetAddress(from));

            msg.setRecipients(javax.mail.Message.RecipientType.TO,
            InternetAddress.parse(username, false));                
            msg.setSubject(subject);
            msg.setContent(body, "text/html");
          // -- Set some other header information --
            msg.setSentDate(new Date());
          // -- Send the message --
            Transport.send(msg);
            //MessageDao.addToHistory(task, new Date(), remindBefore);
          }catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
          }

    }
    private static class SMTPAuthenticator extends javax.mail.Authenticator {
        private PasswordAuthentication authentication;
        public SMTPAuthenticator(String username,String password) {         
            authentication = new PasswordAuthentication(username, password);
        }
        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }

    public static void main(String args[]) throws AddressException, MessagingException
    {
        Mail m=new Mail();


        Mail.sendReminder("this is a test mail");

    }
}*



com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. 7sm50596735paf.22 - gsmtp

    at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1388)
    at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:959)

以下是执行此程序后的错误...我认为有一些问题在那里,如果有可能请检查

1 个答案:

答案 0 :(得分:0)

我认为您只需指定正确的端口,安全电子邮件即可。添加props.put(“mail.smtp.port”,“587”);