使用Java命令发送带有SMTP命令的电子邮件

时间:2010-03-11 06:37:14

标签: java

我正在尝试使用套接字编程通过套接字编程使用套接字在java中发送电子邮件。但我无法这样做。问题在于身份验证可能是。

我需要SMTP命令来发送电子邮件并通过服务器验证用户身份。

任何帮助表示感谢。

先谢谢 伊姆兰

1 个答案:

答案 0 :(得分:0)

创建传输对象

Properties props = new Properties();
        props.setProperty("mail.transport.protocol", pProtocol);
        props.setProperty("mail.host", pHost);
        props.setProperty("mail.user", pUser);
        props.setProperty("mail.password", pPassword);

        mMailSession = Session.getDefaultInstance(props, null);
        mMailSession.setDebug(true);

        try {
            mTransport = mMailSession.getTransport();
            mTransport.connect();
        } catch (MessagingException e) {
            mLog.error(e.getMessage(), e);
            throw new MailException(e);
        }

发送邮件

try {
            MimeMessage message = new MimeMessage(mMailSession);
            message.setSubject(pSubject);

            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setContent(pContent, "text/html");

            Multipart mp = new MimeMultipart();
            mp.addBodyPart(textPart);

            message.setContent(mp);
            message.addFrom(new Address[] { new InternetAddress(pFrom) });

            for (int i = 0; i < pTo.length; i++) {
                String tTo = pTo[i];
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(tTo));
            }

            mTransport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));


        } catch (MessagingException me) {
            throw new MailException(me);
        }

修改

在Thilo的评论之后,我想补充一点,这个解决方案依赖于 com.sun.mail 并导入javax.mail。* classes。