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


206

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

Answers:


190

首先下载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%的方式获得了完整的答案。


1
@varun:这是外发邮件服务器上的端口smtp.gmail.com。有关详细信息,请参见配置其他邮件客户端
比尔蜥蜴

1
我是这里唯一获得AuthenticationFailedException的人props.put(“ mail.smtp.auth”,“ true”); 如果true是字符串。如果它是布尔值就可以了。
nyxz 2011年

2
对于SSL gmail连接,请使用props.put(“ mail.smtp.port”,“ 465”); //而不是587
Tomasz Dziurko

2
有关使用Session.getDefaultInstance(properties)的信息,请参见oracle.com/technetwork/java/faq-135477.html#getdefaultinstance。此常见问题解答建议改为使用getInstance(..)。
Bryan

7
我无法使用具有上述代码和类似代码的SMTP gmail进行访问,javax.mail.AuthenticationFailedException并且必须在我的gmail设置(google.com/settings/security/lesssecureapps)中明确启用“安全程度较低的应用” 。一旦启用了“安全性较低的应用程序”,该代码就会起作用
Marcus Junius Brutus

110

这样的事情(听起来像您只需要更改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();

是否可以将内容发送为html?如果我尝试编写一些html代码并将其发送,但是在接收端,电子邮件的内容仅为html代码。
唐潘

4
要发送html正文而不是明文,请更改以下行:更改message.setText("Welcome to JavaMail");此行:message.setContent("<h1>Hello world</h1>", "text/html");
mist

4
邮件

无需导入一些javalibrary?和@Sotomajor,我们在哪里使用缺失的行?
gumuruh

道具中的@gumuruh。应该是props.put("mail.smtp.starttls.enable", "true")
Sotomajor

21

上面的其他人也有很好的答案,但是我想在这里补充我的经历。我发现,将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>

感谢Jason,感谢您提供配置设置示例以及有关出站邮件限制的警告。我以前从未遇到过限制,但是我确信其他人会发现该信息有用。
比尔蜥蜴

我想进一步了解该垃圾邮件限制...我确实必须发送几封电子邮件,我应该将它们分组吗?等待指定的时间?有人知道Google邮件限制的详细信息吗?
Openas 2010年

12

即使这个问题已经关闭,我也想发布一个对策,但是现在使用简单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 = {"to@gmail.com"};

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);

2
我收到该代码的错误:“消息:一般错误:530 5.7.0必须首先发出STARTTLS命令”-如何使用vesijama启用starttls?
iddqd 2011年

1
我收到“必须先发出STARTTLS命令”错误,因为在下面一行中,我将isStartTlsEnabled变量作为布尔值而不是字符串:props.put(“ mail.smtp.starttls.enable”,isStartTlsEnabled);
user64141 2014年

这个答案:要使用TLS,您可以做类似的事情new Mailer(your login / your session, TransportStrategy.SMTP_TLS).sendMail(email);
Benny Bottema


7

我的完整代码如下所示:

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

public class SendEmail
{
public static void main(String [] args)
{    
    // Sender's email ID needs to be mentioned
     String from = "test@gmail.com";
     String pass ="test123";
    // Recipient's email ID needs to be mentioned.
   String to = "ripon420@yahoo.com";

   String host = "smtp.gmail.com";

   // Get system properties
   Properties properties = System.getProperties();
   // Setup mail server
   properties.put("mail.smtp.starttls.enable", "true");
   properties.put("mail.smtp.host", host);
   properties.put("mail.smtp.user", from);
   properties.put("mail.smtp.password", pass);
   properties.put("mail.smtp.port", "587");
   properties.put("mail.smtp.auth", "true");

   // Get the default Session object.
   Session session = Session.getDefaultInstance(properties);

   try{
      // Create a default MimeMessage object.
      MimeMessage message = new MimeMessage(session);

      // Set From: header field of the header.
      message.setFrom(new InternetAddress(from));

      // Set To: header field of the header.
      message.addRecipient(Message.RecipientType.TO,
                               new InternetAddress(to));

      // Set Subject: header field
      message.setSubject("This is the Subject Line!");

      // Now set the actual message
      message.setText("This is actual message");

      // Send message
      Transport transport = session.getTransport("smtp");
      transport.connect(host, from, pass);
      transport.sendMessage(message, message.getAllRecipients());
      transport.close();
      System.out.println("Sent message successfully....");
   }catch (MessagingException mex) {
      mex.printStackTrace();
   }
}
}

3
//set CLASSPATH=%CLASSPATH%;activation.jar;mail.jar
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class Mail
{
    String  d_email = "iamdvr@gmail.com",
            d_password = "****",
            d_host = "smtp.gmail.com",
            d_port  = "465",
            m_to = "iamdvr@yahoo.com",
            m_subject = "Testing",
            m_text = "Hey, this is the testing email using smtp.gmail.com.";
    public static void main(String[] args)
    {
        String[] to={"XXX@yahoo.com"};
        String[] cc={"XXX@yahoo.com"};
        String[] bcc={"XXX@yahoo.com"};
        //This is for google
        Mail.sendMail("venkatesh@dfdf.com", "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("p_sambasivarao@sutyam.com"));
            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;
        }
    }

}

3

最低要求:

import java.util.Properties;

import javax.mail.Message;
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 MessageSender {

    public static void sendHardCoded() throws AddressException, MessagingException {
        String to = "a@a.info";
        final String from = "b@gmail.com";

        Properties properties = new Properties();
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.port", "587");

        Session session = Session.getInstance(properties,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(from, "BeNice");
                    }
                });

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject("Hello");
        message.setText("What's up?");

        Transport.send(message);
    }

}

1
@ AlikElizin-kilaka我试图同时使用发件人和收件人的gmail ID,发现您还需要在Google帐户设置中将“允许安全程度较低的应用程序”标志设置为“开”,因为您使用的安全性较低的Gmail配置文件方式。然后,只有您才能看到从Java客户端发送的电子邮件。否则,您将获得javax.mail.AuthenticationFailedException。
kunal

2

当您需要在同一JVM中的任何地方设置多个SMTP会话时,发布的代码解决方案可能会导致问题。

JavaMail FAQ建议使用

Session.getInstance(properties);

代替

Session.getDefaultInstance(properties);

因为getDefault将仅使用首次调用给定的属性。以后对默认实例的所有使用都会忽略属性更改。

请参阅http://www.oracle.com/technetwork/java/faq-135477.html#getdefaultinstance


1

当我要发送带有附件的电子邮件时,这就是我的工作,可以正常工作。:)

 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("username-gmail@gmail.com"));
            msg.setSubject("Try attachment gmail");
            msg.setRecipient(RecipientType.TO, new InternetAddress("username-gmail@gmail.com"));
            //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);
        }
    }

}

0

一个简单的方法是为POP3访问配置/启用Gmail帐户。这将允许您通过gmail服务器通过普通SMTP发送出去。

然后,您只需通过smtp.gmail.com发送(在端口587上)


0

嗨,尝试这段代码。

package my.test.service;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Sample {
    public static void main(String args[]) {
        final String SMTP_HOST = "smtp.gmail.com";
        final String SMTP_PORT = "587";
        final String GMAIL_USERNAME = "xxxxxxxxxx@gmail.com";
        final String GMAIL_PASSWORD = "xxxxxxxxxx";

        System.out.println("Process Started");

        Properties prop = System.getProperties();
        prop.setProperty("mail.smtp.starttls.enable", "true");
        prop.setProperty("mail.smtp.host", SMTP_HOST);
        prop.setProperty("mail.smtp.user", GMAIL_USERNAME);
        prop.setProperty("mail.smtp.password", GMAIL_PASSWORD);
        prop.setProperty("mail.smtp.port", SMTP_PORT);
        prop.setProperty("mail.smtp.auth", "true");
        System.out.println("Props : " + prop);

        Session session = Session.getInstance(prop, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(GMAIL_USERNAME,
                        GMAIL_PASSWORD);
            }
        });

        System.out.println("Got Session : " + session);

        MimeMessage message = new MimeMessage(session);
        try {
            System.out.println("before sending");
            message.setFrom(new InternetAddress(GMAIL_USERNAME));
            message.addRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(GMAIL_USERNAME));
            message.setSubject("My First Email Attempt from Java");
            message.setText("Hi, This mail came from Java Application.");
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(GMAIL_USERNAME));
            Transport transport = session.getTransport("smtp");
            System.out.println("Got Transport" + transport);
            transport.connect(SMTP_HOST, GMAIL_USERNAME, GMAIL_PASSWORD);
            transport.sendMessage(message, message.getAllRecipients());
            System.out.println("message Object : " + message);
            System.out.println("Email Sent Successfully");
        } catch (AddressException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

0

这是一个易于使用的类,用于通过发送电子邮件Gmail。您需要将JavaMail添加到构建路径或只使用Maven

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class GmailSender
{
    private static String protocol = "smtp";

    private String username;
    private String password;

    private Session session;
    private Message message;
    private Multipart multipart;

    public GmailSender()
    {
        this.multipart = new MimeMultipart();
    }

    public void setSender(String username, String password)
    {
        this.username = username;
        this.password = password;

        this.session = getSession();
        this.message = new MimeMessage(session);
    }

    public void addRecipient(String recipient) throws AddressException, MessagingException
    {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
    }

    public void setSubject(String subject) throws MessagingException
    {
        message.setSubject(subject);
    }

    public void setBody(String body) throws MessagingException
    {
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body);
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);
    }

    public void send() throws MessagingException
    {
        Transport transport = session.getTransport(protocol);
        transport.connect(username, password);
        transport.sendMessage(message, message.getAllRecipients());

        transport.close();
    }

    public void addAttachment(String filePath) throws MessagingException
    {
        BodyPart messageBodyPart = getFileBodyPart(filePath);
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);
    }

    private BodyPart getFileBodyPart(String filePath) throws MessagingException
    {
        BodyPart messageBodyPart = new MimeBodyPart();
        DataSource dataSource = new FileDataSource(filePath);
        messageBodyPart.setDataHandler(new DataHandler(dataSource));
        messageBodyPart.setFileName(filePath);

        return messageBodyPart;
    }

    private Session getSession()
    {
        Properties properties = getMailServerProperties();
        Session session = Session.getDefaultInstance(properties);

        return session;
    }

    private Properties getMailServerProperties()
    {
        Properties properties = System.getProperties();
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", protocol + ".gmail.com");
        properties.put("mail.smtp.user", username);
        properties.put("mail.smtp.password", password);
        properties.put("mail.smtp.port", "587");
        properties.put("mail.smtp.auth", "true");

        return properties;
    }
}

用法示例:

GmailSender sender = new GmailSender();
sender.setSender("myEmailNameWithout@gmail.com", "mypassword");
sender.addRecipient("recipient@somehost.com");
sender.setSubject("The subject");
sender.setBody("The body");
sender.addAttachment("TestFile.txt");
sender.send();


0

增加值:

  • 编码主题,消息和显示名称的陷阱
  • 现代Java邮件库版本需要一个魔术属性
  • Session.getInstance() 推荐过来 Session.getDefaultInstance()
  • 同一示例中的附件
  • Google关闭安全性较低的应用程序仍然可以使用:在您的组织中启用2要素身份验证->打开2FA->生成应用程序密码。
    import java.io.File;
    import java.nio.charset.StandardCharsets;
    import java.util.Properties;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.activation.DataHandler;
    import javax.mail.Message;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;
    import javax.mail.util.ByteArrayDataSource;
    
    public class Gmailer {
      private static final Logger LOGGER = Logger.getLogger(Gmailer.class.getName());
    
      public static void main(String[] args) {
        send();
      }
    
      public static void send() {
        Transport transport = null;
        try {
          String accountEmail = "account@source.com";
          String accountAppPassword = "";
          String displayName = "Display-Name 東";
          String replyTo = "reply-to@source.com";
    
          String to = "to@target.com";
          String cc = "cc@target.com";
          String bcc = "bcc@target.com";
    
          String subject = "Subject 東";
          String message = "<span style='color: red;'>東</span>";
          String type = "html"; // or "plain"
          String mimeTypeWithEncoding = "text/" + type + "; charset=" + StandardCharsets.UTF_8.name();
    
          File attachmentFile = new File("Attachment.pdf");
          // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
          String attachmentMimeType = "application/pdf";
          byte[] bytes = ...; // read file to byte array
    
          Properties properties = System.getProperties();
          properties.put("mail.debug", "true");
          // i found that this is the only property necessary for a modern java mail version
          properties.put("mail.smtp.starttls.enable", "true");
          // https://javaee.github.io/javamail/FAQ#getdefaultinstance
          Session session = Session.getInstance(properties);
    
          MimeMessage mimeMessage = new MimeMessage(session);
    
          // probably best to use the account email address, to avoid landing in spam or blacklists
          // not even sure if the server would accept a differing from address
          InternetAddress from = new InternetAddress(accountEmail);
          from.setPersonal(displayName, StandardCharsets.UTF_8.name());
          mimeMessage.setFrom(from);
    
          mimeMessage.setReplyTo(InternetAddress.parse(replyTo));
    
          mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
          mimeMessage.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
          mimeMessage.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
    
          mimeMessage.setSubject(subject, StandardCharsets.UTF_8.name());
    
          MimeMultipart multipart = new MimeMultipart();
    
          MimeBodyPart messagePart = new MimeBodyPart();
          messagePart.setContent(mimeMessage, mimeTypeWithEncoding);
          multipart.addBodyPart(messagePart);
    
          MimeBodyPart attachmentPart = new MimeBodyPart();
          attachmentPart.setDataHandler(new DataHandler(new ByteArrayDataSource(bytes, attachmentMimeType)));
          attachmentPart.setFileName(attachmentFile.getName());
          multipart.addBodyPart(attachmentPart);
    
          mimeMessage.setContent(multipart);
    
          transport = session.getTransport();
          transport.connect("smtp.gmail.com", 587, accountEmail, accountAppPassword);
          transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        }
        catch(Exception e) {
          // I prefer to bubble up exceptions, so the caller has the info that someting went wrong, and gets a chance to handle it.
          // I also prefer not to force the exception in the signature.
          throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
        }
        finally {
          if(transport != null) {
            try {
              transport.close();
            }
            catch(Exception e) {
              LOGGER.log(Level.WARNING, "failed to close java mail transport: " + e);
            }
          }
        }
      }
    }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.