简短回答:您可以使用 gen_smtp 发送带有附件的电子邮件。
如果您使用过gen_smtp_client:send(Email, Options) 或gen_smtp_client:send_blocking(Email, Options),那么您实际上可以使用mimemail:encode/2 生成Body's Email 变量。
%% @doc Encode a MIME tuple to a binary.
encode({Type, Subtype, Headers, ContentTypeParams, Parts}, Options) ->
...
下面的代码显示了如何发送带有电子邮件内联正文和 2 个附件(分别为test1.txt 和 erlang.png)的消息。这里的关键是使用multipart/mixed MIME 类型并相应地构造电子邮件正文。
send_email_with_attachment() ->
From = "noreply@mydomain.com",
ToList = ["target_email@mydomain.com"],
Part2Filename = "/tmp/test1.txt",
{ok, Part2Binary} = file:read_file(Part2Filename),
Part3Filename = "/tmp/erlang.png",
{ok, Part3Binary} = file:read_file(Part3Filename),
Email = mimemail:encode(
{
<<"multipart">>, %%Type,
<<"mixed">>, %%Subtype,
%%Headers,
[
{<<"From">>, <<"No-Reply <noreply@mydomain.com>">>},
{<<"To">>, <<"target_email@mydomain.com">>},
{<<"Subject">>, <<"Mail Subject">>}
],
#{}, %%[], %%ContentTypeParams,
%%(Multi)Parts
[
%%Part 1: this is the inline mail body, note the {<<"disposition">>, <<"inline">>} tag
{
<<"text">>, %%Type,
<<"plain">>, %%Subtype,
%%Headers
[],
%%ContentTypeParams
#{
disposition => <<"inline">>
},
%%Part
<<"Email body (inline) is here blah blah..">>
},
%%Part 2: this is the text file as attachment, note the {<<"disposition">>, <<"attachment">>} tag
{
<<"text">>, %%Type,
<<"plain">>, %%Subtype,
%%Headers
[],
%%ContentTypeParams
#{
disposition => <<"attachment">>,
disposition_params => [{<<"filename">>, <<"test1.txt">>}]
},
%%Part
Part2Binary
},
%%Part 3: this is the PNG file as attachment, note the {<<"disposition">>, <<"attachment">>} tag
{
<<"image">>, %%Type,
<<"png">>, %%Subtype,
%%Headers
[],
%%ContentTypeParams
#{
disposition => <<"attachment">>,
disposition_params => [{<<"filename">>, <<"erlang.png">>}]
},
%%Part
Part3Binary
}
]
},
[] %%Options
),
Opts = [{relay, "smtp.mydomain.com"},
{tls, never}
],
gen_smtp_client:send({From, ToList, Email}, Opts).
这是您将在邮箱中看到的内容: