所以我的可移植类库中有这个按钮,它应该直接将我创建的xml文件附加到邮件中并使用Messaging PlugIn发送它。问题是。在PCL中不支持.WithAttachment()所以我想问一下我是否可以使用DependencyService来解决这个问题,如果是的话,怎么做?
我可以从UWP类返回.WithAttachment()(因为UWP是我的目标平台)吗?不会有冲突,因为我已经读过UWP中.WithAttachment()的重载是.WithAttachment(IStorageFile文件)。
private void Senden_Clicked(object sender, EventArgs e)
{
var emailMessenger = CrossMessaging.Current.EmailMessenger;
if (emailMessenger.CanSendEmail)
{
var email = new EmailMessageBuilder()
.To("my.address@gmail.com")
.Subject("Test")
.Body("Hello there!")
//.WithAttachment(String FilePath, string ContentType) overload showing in PCL
//.WithAttachment(IStorageFile file) overload for the UWP according to the documentation
.Build();
emailMessenger.SendEmail(email);
}
}
修改
我已经能够修改Nick Zhou的答案,以便能够通过按钮点击发送带附件的电子邮件。我只是改变了代码的和平:
var picker = new Windows.Storage.Pickers.FileOpenPicker
{
ViewMode = Windows.Storage.Pickers.PickerViewMode.List,
SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary
};
picker.FileTypeFilter.Add("*");
到此:
StorageFolder sf = ApplicationData.Current.LocalFolder;
var file = await sf.GetFileAsync("daten.xml");
当然,您需要在应用程序的本地文件夹而不是文档库中创建文件。
答案 0 :(得分:1)
问题是。在PCL中不支持.WithAttachment()所以我想问一下我是否可以使用DependencyService来解决这个问题,如果是的话,怎么做?
当然,您可以使用DependencyService
来实现发送电子邮件。但你可以在后面创建两个interface
代码。
SendEmail接口
public interface IMessageEmail
{
void SendEmailMehod(string address, string subject, string body, StorageFile attactment = null);
}
UWP项目中的IMessageEmail实现。
public void SendEmailMehod(string address, string subject, string body, StorageFile attactment = null)
{
var emailMessenger = CrossMessaging.Current.EmailMessenger;
if (emailMessenger.CanSendEmail)
{
if (attactment != null)
{
var email = new EmailMessageBuilder()
.To(address)
.Subject(subject)
.Body(body)
.WithAttachment(attactment)
.Build();
emailMessenger.SendEmail(email);
}
else
{
var email = new EmailMessageBuilder()
.To(address)
.Subject(subject)
.Body(body)
.Build();
emailMessenger.SendEmail(email);
}
}
}
正如您所见,.WithAttachment(attactment)
参数为IStorageFile
。所以你需要将文件传递给方法。因此,您可以创建另一个DependencyService
。
IFilePicker接口
public interface IFilePicker
{
Task<StorageFile> getFileAsync();
}
UWP项目中的IMessageEmail实现。
public async Task<StorageFile> getFileAsync()
{
var picker = new Windows.Storage.Pickers.FileOpenPicker
{
ViewMode = Windows.Storage.Pickers.PickerViewMode.List,
SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary
};
picker.FileTypeFilter.Add("*");
var file = await picker.PickSingleFileAsync();
if (file != null)
{
return file;
}
return null;
}
您可以尝试我上传到github的project。