最近,我在Java netbeans中创建了Web应用程序并且我制作了注册和登录系统,请告诉我如何使用java发送电子邮件,因此当用户注册时,他将在他的电子邮件中收到欢迎消息。我只想要发送电子邮件的代码。
答案 0 :(得分:1)
来自here:
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
public class SendMailUsingAuthentication
{
private static final String SMTP_HOST_NAME = "gemini.jvmhost.com"; //or simply "localhost"
private static final String SMTP_AUTH_USER = "me@domain.com";
private static final String SMTP_AUTH_PWD = "secret";
private static final String emailMsgTxt = "Body";
private static final String emailSubjectTxt = "Subject";
private static final String emailFromAddress = "me@domain.com";
// Add List of Email address to who email needs to be sent to
private static final String[] emailList = {"he@domain.net"};
public static void main(String args[]) throws Exception
{
SendMailUsingAuthentication smtpMailSender = new SendMailUsingAuthentication();
smtpMailSender.postMail( emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
System.out.println("Sucessfully Sent mail to All Users");
}
public void postMail( String recipients[ ], String subject,
String message , String from) throws MessagingException, AuthenticationFailedException
{
boolean debug = false;
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
{
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}
private class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}
}
如果您需要进一步的帮助,请告诉我,我会帮助您。
答案 1 :(得分:1)
public static void main(String[] args){
final String fromEmail = "from Emailid";//user.getFromEmail(); //requires valid gmail id
final String password = " password of from emailid";//user.getPassword(); // correct password for gmail id
final String toEmail = "to emailid"; // can be any email id
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
props.put("mail.smtp.port", "587"); //TLS Port
props.put("mail.smtp.auth", "true"); //enable authentication
props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
//enable authentication
try
{
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password.toCharArray());
}
};
Session session = Session.getDefaultInstance(props,null);
MimeMessage msg = new MimeMessage(session);
//set message headers
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress(fromEmail, "Rameshwar Agarwal"));
msg.setReplyTo(InternetAddress.parse(fromEmail, false));
msg.setSubject("app test email", "UTF-8");
msg.setText("hello Rameshwar", "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
System.out.println("Message is ready");
Transport trans=session.getTransport("smtp");
trans.connect("smtp.gmail.com",fromEmail,password);
trans.sendMessage(msg,msg.getAllRecipients());
System.out.println("EMail Sent Successfully!!");
}
catch (Exception e) {
e.printStackTrace();
}
}
答案 2 :(得分:0)
以下代码适用于Google SMTP服务器。您需要提供Google用户名和密码。 (别忘了下载JavaMail API)
import com.sun.mail.smtp.SMTPTransport;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class GoogleMail {
private GoogleMail() {
}
/**
* Send email using GMail SMTP server.
*
* @param username GMail username
* @param password GMail password
* @param recipientEmail TO recipient
* @param title title of the message
* @param message message to be sent
* @throws AddressException if the email address parse failed
* @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
*/
public static void Send(final String username, final String password, String recipientEmail, String title, String message) throws AddressException, MessagingException {
GoogleMail.Send(username, password, recipientEmail, "", title, message);
}
/**
* Send email using GMail SMTP server.
*
* @param username GMail username
* @param password GMail password
* @param recipientEmail TO recipient
* @param ccEmail CC recipient. Can be empty if there is no CC recipient
* @param title title of the message
* @param message message to be sent
* @throws AddressException if the email address parse failed
* @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
*/
public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Get a Properties object
Properties props = System.getProperties();
props.setProperty("mail.smtps.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.setProperty("mail.smtps.auth", "true");
/*
If set to false, the QUIT command is sent and the connection is immediately closed. If set
to true (the default), causes the transport to wait for the response to the QUIT command.
ref : http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html
http://forum.java.sun.com/thread.jspa?threadID=5205249
smtpsend.java - demo program from javamail
*/
props.put("mail.smtps.quitwait", "false");
Session session = Session.getInstance(props, null);
// -- Create a new message --
final MimeMessage msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(username + "@gmail.com"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));
if (ccEmail.length() > 0) {
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
}
msg.setSubject(title);
msg.setText(message, "utf-8");
msg.setSentDate(new Date());
SMTPTransport t = (SMTPTransport)session.getTransport("smtps");
t.connect("smtp.gmail.com", username, password);
t.sendMessage(msg, msg.getAllRecipients());
t.close();
}
}
答案 3 :(得分:0)
在这里,您可以找到为使用Google帐户发送电子邮件而编写的示例java类。 请按照以下link
进行操作它使用以下属性
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");