如何通过Java应用程序使用GMail,Yahoo或者Hotmail发送电子邮件?
是否可以使用GMail帐户从Java应用程序发送电子邮件?我已经用Java应用程序配置了我的公司邮件服务器来发送电子邮件,但是在分发应用程序时并不会减少它。任何使用Hotmail,Yahoo或者GMail的答案都是可以接受的。
解决方案
回答
一个简单的方法是为POP3访问配置/启用Gmail帐户。这将允许我们通过gmail服务器通过普通SMTP发送出去。
然后,我们只需通过smtp.gmail.com发送(在端口587上)
回答
这样的事情(听起来像我们只需要更改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();
回答
首先下载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 = "[email protected]"; 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%的方式获得了完整的答案。
回答
即使这个问题已经关闭,我也想发布一个对策,但是现在使用简单Java Mail(开放源JavaMail smtp包装器):
final Email email = new Email(); String host = "smtp.gmail.com"; Integer port = 587; String from = "username"; String pass = "password"; String[] to = {"[email protected]"}; email.setFromAddress("", from); email.setSubject("sending in a group"); for( int i=0; i < to.length; i++ ) { email.addRecipient("", to[i], RecipientType.TO); } email.setText("Welcome to JavaMail"); new Mailer(host, port, from, pass).sendMail(email); // you could also still use your mail session instead new Mailer(session).sendMail(email);
回答
当我想发送带有附件的电子邮件时,这就是我的工作,可以正常工作。 :)
public class NewClass { public static void main(String[] args) { try { Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); // smtp port Authenticator auth = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username-gmail", "password-gmail"); } }; Session session = Session.getDefaultInstance(props, auth); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress("[email protected]")); msg.setSubject("Try attachment gmail"); msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]")); //add atleast simple body MimeBodyPart body = new MimeBodyPart(); body.setText("Try attachment"); //do attachment MimeBodyPart attachMent = new MimeBodyPart(); FileDataSource dataSource = new FileDataSource(new File("file-sent.txt")); attachMent.setDataHandler(new DataHandler(dataSource)); attachMent.setFileName("file-sent.txt"); attachMent.setDisposition(MimeBodyPart.ATTACHMENT); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(body); multipart.addBodyPart(attachMent); msg.setContent(multipart); Transport.send(msg); } catch (AddressException ex) { Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex); } catch (MessagingException ex) { Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex); } } }
回答
上面的其他人也有很好的答案,但是我想在这里补充我的经验。我发现,将Gmail用作Web应用程序的出站SMTP服务器时,Gmail仅允许我发送约10封左右的邮件,然后再进行反垃圾邮件响应,而我必须手动执行此步骤才能重新启用SMTP访问。当用户向我的系统注册时,我发送的电子邮件不是垃圾邮件,而是网站"欢迎"电子邮件。因此,YMMV,而且我不会将Gmail用于生产Web应用程序。如果我们是代表用户发送电子邮件,例如已安装的桌面应用程序(用户在其中输入自己的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>
回答
//set CLASSPATH=%CLASSPATH%;activation.jar;mail.jar import javax.mail.*; import javax.mail.internet.*; import java.util.*; public class Mail { String d_email = "[email protected]", d_password = "****", d_host = "smtp.gmail.com", d_port = "465", m_to = "[email protected]", m_subject = "Testing", m_text = "Hey, this is the testing email using smtp.gmail.com."; public static void main(String[] args) { String[] to={"[email protected]"}; String[] cc={"[email protected]"}; String[] bcc={"[email protected]"}; //This is for google Mail.sendMail("[email protected]", "password", "smtp.gmail.com", "465", "true", "true", true, "javax.net.ssl.SSLSocketFactory", "false", to, cc, bcc, "hi baba don't send virus mails..", "This is my style...of reply..If u send virus mails.."); } public synchronized static boolean sendMail( String userName, String passWord, String host, String port, String starttls, String auth, boolean debug, String socketFactoryClass, String fallback, String[] to, String[] cc, String[] bcc, String subject, String text) { Properties props = new Properties(); //Properties props=System.getProperties(); props.put("mail.smtp.user", userName); props.put("mail.smtp.host", host); if(!"".equals(port)) props.put("mail.smtp.port", port); if(!"".equals(starttls)) props.put("mail.smtp.starttls.enable",starttls); props.put("mail.smtp.auth", auth); if(debug) { props.put("mail.smtp.debug", "true"); } else { props.put("mail.smtp.debug", "false"); } if(!"".equals(port)) props.put("mail.smtp.socketFactory.port", port); if(!"".equals(socketFactoryClass)) props.put("mail.smtp.socketFactory.class",socketFactoryClass); if(!"".equals(fallback)) props.put("mail.smtp.socketFactory.fallback", fallback); try { Session session = Session.getDefaultInstance(props, null); session.setDebug(debug); MimeMessage msg = new MimeMessage(session); msg.setText(text); msg.setSubject(subject); msg.setFrom(new InternetAddress("[email protected]")); for(int i=0;i<to.length;i++) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i])); } for(int i=0;i<cc.length;i++) { msg.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i])); } for(int i=0;i<bcc.length;i++) { msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[i])); } msg.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(host, userName, passWord); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); return true; } catch (Exception mex) { mex.printStackTrace(); return false; } } }