如何通过Java应用程序使用GMail,Yahoo或Hotmail发送电子邮件?

是否可以使用GMail帐户从我的Java应用程序发送电子邮件? 我已经使用Java应用程序配置了我的公司邮件服务器来发送电子邮件,但是当我分发应用程序时,这不会削减它。 任何使用Hotmail,Yahoo或GMail的答案都可以接受。


首先下载JavaMail API并确保相关的jar文件位于你的类路径中。

这里有一个使用GMail的完整工作示例。

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class Main {

    private static String USER_NAME = "*****";  // GMail user name (just the part before "@gmail.com")
    private static String PASSWORD = "********"; // GMail password
    private static String RECIPIENT = "lizard.bill@myschool.edu";

    public static void main(String[] args) {
        String from = USER_NAME;
        String pass = PASSWORD;
        String[] to = { RECIPIENT }; // list of recipient email addresses
        String subject = "Java send mail example";
        String body = "Welcome to JavaMail!";

        sendFromGMail(from, pass, to, subject, body);
    }

    private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
        Properties props = System.getProperties();
        String host = "smtp.gmail.com";
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);
        MimeMessage message = new MimeMessage(session);

        try {
            message.setFrom(new InternetAddress(from));
            InternetAddress[] toAddress = new InternetAddress[to.length];

            // To get the array of addresses
            for( int i = 0; i < to.length; i++ ) {
                toAddress[i] = new InternetAddress(to[i]);
            }

            for( int i = 0; i < toAddress.length; i++) {
                message.addRecipient(Message.RecipientType.TO, toAddress[i]);
            }

            message.setSubject(subject);
            message.setText(body);
            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        }
        catch (AddressException ae) {
            ae.printStackTrace();
        }
        catch (MessagingException me) {
            me.printStackTrace();
        }
    }
}

当然,你需要在catch块中做更多的事情,而不是像上面的代码那样打印栈跟踪。 (删除catch块以查看来自JavaMail API的哪些方法调用会抛出异常,以便更好地了解如何正确处理它们。)


感谢@jodonnel和其他所有回答。 我给了他一笔赏金,因为他的回答使我获得了95%的答案。


像这样的东西(听起来像你只需要改变你的SMTP服务器):

String host = "smtp.gmail.com";
String from = "user name";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "asdfgh");
props.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mail
props.put("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));

InternetAddress[] to_address = new InternetAddress[to.length];
int i = 0;
// To get the array of addresses
while (to[i] != null) {
    to_address[i] = new InternetAddress(to[i]);
    i++;
}
System.out.println(Message.RecipientType.TO);
i = 0;
while (to_address[i] != null) {

    message.addRecipient(Message.RecipientType.TO, to_address[i]);
    i++;
}
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
// alternately, to send HTML mail:
// message.setContent("<p>Welcome to JavaMail</p>", "text/html");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.mail.yahoo.co.in", "user name", "asdfgh");
transport.sendMessage(message, message.getAllRecipients());
transport.close();

其他人在上面有很好的答案,但我想在这里添加一个关于我的经验的笔记。 我发现,当使用Gmail作为我的web应用程序的出站SMTP服务器时,Gmail只允许我发送大约10条左右的消息,然后再响应我的垃圾邮件响应,我必须手动逐步重新启用SMTP访问。 我发送的电子邮件不是垃圾邮件,而是当用户在我的系统中注册时发送的网站“欢迎”电子邮件。 所以,YMMV,我不会依赖Gmail来制作webapp。 如果您代表用户发送电子邮件,例如安装的桌面应用程序(用户输入他们自己的Gmail凭据),则可能没问题。

另外,如果您使用的是Spring,那么可以使用Gmail作为出站SMTP的工作配置:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="defaultEncoding" value="UTF-8"/>
    <property name="host" value="smtp.gmail.com"/>
    <property name="port" value="465"/>
    <property name="username" value="${mail.username}"/>
    <property name="password" value="${mail.password}"/>
    <property name="javaMailProperties">
        <value>
            mail.debug=true
            mail.smtp.auth=true
            mail.smtp.socketFactory.class=java.net.SocketFactory
            mail.smtp.socketFactory.fallback=false
        </value>
    </property>
</bean>
链接地址: http://www.djcxy.com/p/50529.html

上一篇: How can I send an email by Java application using GMail, Yahoo, or Hotmail?

下一篇: How to send an email in .Net according to new security policies?